forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0701-insert-into-a-binary-search-tree.java
37 lines (36 loc) · 1.12 KB
/
0701-insert-into-a-binary-search-tree.java
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
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) return new TreeNode(val);
TreeNode curr = root;
while(true){
if(curr.val <= val){
if(curr.right != null){
curr = curr.right;
}else{
curr.right = new TreeNode(val);
break;
}
}else{
if(curr.left != null) curr = curr.left;
else{
curr.left = new TreeNode(val);
break;
}
}
}
return root;
}
/* Using Recursive Solution
-------------------------------------------------------------------
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) return new TreeNode(val);
if(root.val <= val){
root.right = insertIntoBST(root.right, val);
}else{
root.left = insertIntoBST(root.left, val);
}
return root;
}
-------------------------------------------------------------------
*/
}