forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert-node-in-a-binary-search-tree(AC).cpp
More file actions
46 lines (46 loc) · 1.15 KB
/
insert-node-in-a-binary-search-tree(AC).cpp
File metadata and controls
46 lines (46 loc) · 1.15 KB
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
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
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 == NULL) {
return node;
}
TreeNode *ptr = root;
while (true) {
if (node->val < ptr->val) {
if (ptr->left == NULL) {
ptr->left = node;
break;
} else {
ptr = ptr->left;
}
} else if (node->val > ptr->val) {
if (ptr->right == NULL) {
ptr->right = node;
break;
} else {
ptr = ptr->right;
}
} else {
break;
}
}
return root;
}
};