-
Notifications
You must be signed in to change notification settings - Fork 258
/
insert-node-in-a-binary-search-tree.cpp
64 lines (62 loc) · 1.68 KB
/
insert-node-in-a-binary-search-tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Time: O(h)
// Space: O(1)
class Solution {
public:
/**
* @param root: The root of the binary search tree->
* @param node: insert this node into the binary search tree
* @return: The root of the new binary search tree->
*/
TreeNode* insertNode(TreeNode* root, TreeNode* node) {
if (root == nullptr) {
return node;
}
TreeNode* curr = root;
while (true) {
if (node->val < curr->val) {
if (curr->left != nullptr) {
curr = curr->left;
}
else {
curr->left = node;
break;
}
} else if (node->val > curr->val) {
if (curr->right != nullptr) {
curr = curr->right;
}
else {
curr->right = node;
break;
}
} else {
curr->val = node->val;
break;
}
}
return root;
}
};
class Solution2 {
public:
/**
* @param root: The root of the binary search tree->
* @param node: insert this node into the binary search tree
* @return: The root of the new binary search tree->
*/
TreeNode* insertNode(TreeNode* root, TreeNode* node) {
if (root == nullptr) {
return node;
}
if (node->val < root->val) {
root->left = insertNode(root->left, node);
}
else if (node->val > root->val) {
root->right = insertNode(root->right, node);
}
else {
root->val = node->val;
}
return root;
}
};