-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathInsertIntoBST.java
49 lines (43 loc) · 1.29 KB
/
InsertIntoBST.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
38
39
40
41
42
43
44
45
46
47
48
49
/*https://leetcode.com/problems/insert-into-a-binary-search-tree/*/
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
//if root is null
if (root == null)
{
//insert at root and return
root = new TreeNode(val);
return root;
}
//recursion call
TreeNode treeRoot = insertNode(root, val);
return treeRoot;
}
public TreeNode insertNode(TreeNode root, int val)
{
//if value is less than root value and left subtree is null
if (val < root.val && root.left == null)
{
//insert at left and return
root.left = new TreeNode(val);
return root;
}
//if value is greater than root value and right subtree is null
if (val > root.val && root.right == null)
{
//insert at right and return
root.right = new TreeNode(val);
return root;
}
//if value is less than root value
if (val < root.val)
{
/*recursion*/
//insert in the left subtree and return
insertNode(root.left,val);
return root;
}
//insert in the right subtree and return
insertNode(root.right,val);
return root;
}
}