-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsert Node in a Binary Search Tree.cpp
68 lines (64 loc) · 1.45 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
65
66
67
68
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include "model.h"
using namespace std;
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) {
// write your code here
if(!root) {
return node;
}
TreeNode *cur = root;
while(cur) {
if(cur->val <= node->val) {
if(cur->right) {
cur = cur->right;
}
else {
cur->right = node;
break;
}
}
else if(cur->val > node->val) {
if(cur->left) {
cur = cur->left;
}
else {
cur->left = node;
break;
}
}
}
return root;
}
};
TreeNode *buildTree(int depth, int val) {
TreeNode *root = new TreeNode(val);
if(depth == 0) {
return root;
}
root->left = buildTree(depth - 1, val - 1);
root->right = buildTree(depth - 1, val + 1);
return root;
}
int main() {
int val = 1;
TreeNode *tree = buildTree(1, val);
bfsCodec code;
string res1 = code.serialize(tree);
cout << res1 << endl;
Solution s;
TreeNode *node = new TreeNode(5);
TreeNode *root = s.insertNode(tree, node);
string res = code.serialize(root);
cout << res << endl;
return 0;
}