Skip to content

Commit 450bdf7

Browse files
authored
Create 0701-insertion-into-a-binary-search-tree.cpp
1 parent 007c6a6 commit 450bdf7

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
You are given the root node of a binary search tree (BST) and a value to insert into the tree.
3+
Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
4+
5+
Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion.
6+
You can return any of them.
7+
8+
Ex. Input: root = [4,2,7,1,3], val = 5
9+
Output: [4,2,7,1,3,5]
10+
11+
Time : O(N)
12+
Space : O(N)
13+
*/
14+
15+
/**
16+
* Definition for a binary tree node.
17+
* struct TreeNode {
18+
* int val;
19+
* TreeNode *left;
20+
* TreeNode *right;
21+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
22+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
23+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
24+
* };
25+
*/
26+
class Solution {
27+
public:
28+
TreeNode * create(int val) {
29+
TreeNode *n = new TreeNode;
30+
n -> val = val;
31+
n -> left = n -> right = NULL;
32+
return n;
33+
}
34+
35+
TreeNode* insertIntoBST(TreeNode* root, int val) {
36+
if(root == NULL)
37+
return create(val);
38+
39+
else if(val > root -> val)
40+
root -> right = insertIntoBST(root -> right, val);
41+
else if(val < root -> val)
42+
root -> left = insertIntoBST(root -> left, val);
43+
return root;
44+
}
45+
};

0 commit comments

Comments
 (0)