Skip to content

Commit 59f628b

Browse files
author
Sherali Obidov
committed
today's contribution, medium problem, insert into bst, can u make such neat solution
1 parent 07e703b commit 59f628b

2 files changed

Lines changed: 50 additions & 0 deletions

File tree

‎src/problems/Medium.txt‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2949,3 +2949,33 @@ Output: true
29492949
Note:
29502950

29512951
1 <= N <= 10^9
2952+
195) Insert Into Binary Search Tree
2953+
Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
2954+
2955+
Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.
2956+
2957+
For example,
2958+
2959+
Given the tree:
2960+
4
2961+
/ \
2962+
2 7
2963+
/ \
2964+
1 3
2965+
And the value to insert: 5
2966+
You can return this binary search tree:
2967+
2968+
4
2969+
/ \
2970+
2 7
2971+
/ \ /
2972+
1 3 5
2973+
This tree is also valid:
2974+
2975+
5
2976+
/ \
2977+
2 7
2978+
/ \
2979+
1 3
2980+
\
2981+
4
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package problems.medium;
2+
3+
import problems.utils.TreeNode;
4+
5+
/**
6+
* Why Did you create this class? what does it do?
7+
*/
8+
public class InsertIntoBST {
9+
public TreeNode insertIntoBST(TreeNode root, int val) {
10+
if (root == null)
11+
return new TreeNode(val);
12+
13+
if (root.val < val)
14+
root.right = insertIntoBST(root.right, val);
15+
else
16+
root.left = insertIntoBST(root.left, val);
17+
18+
return root;
19+
}
20+
}

0 commit comments

Comments
 (0)