-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path701-insert-into-a-binary-search-tree.cpp
40 lines (39 loc) · 1.13 KB
/
701-insert-into-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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
//Exception Handling in case of Empty BST
if (!(root))
return new TreeNode(val);
bool childDir; //Direction of Child - Left(false) or Right(true)
// Traverse given BST
auto ptr = root;
auto prev = ptr;
while(ptr){
prev = ptr;
if (val>ptr->val){
ptr = ptr->right;
childDir = true;
}
else{
ptr=ptr->left;
childDir = false;
}
}
// Insert `val` in correct child position
if(childDir)
prev->right = new TreeNode(val);
else prev->left = new TreeNode(val);
return root;
}
};