-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchInsert.java
More file actions
40 lines (32 loc) · 1.21 KB
/
SearchInsert.java
File metadata and controls
40 lines (32 loc) · 1.21 KB
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
package BinarySearchTrees;
/**
* Insertion And Deletion are two most important parts of a BSt.
*/
public class SearchInsert {
public static Node insertIntoBST(Node root, int val) {
if (root == null) return new Node(val);
if (root.val > val) {
if (root.left == null) root.left = new Node(val);
else insertIntoBST(root.left, val);
} else if (root.val < val) {
if (root.right == null) root.right = new Node(val);
else insertIntoBST(root.right, val);
}
return root;
}
public static Node searchBST(Node root, int val) {
if (root == null) return null;
if (root.val == val) return root;
else if (root.val < val) return searchBST(root.right, val);
else return searchBST(root.left, val);
}
public static void main(String[] args) {
String[] arr = {"50", "20", "60", "17", "34", "55", "89", "10", "", "28", "", "", "", "70", "", "", "14"};
Node root = Construct.construct(arr);
Node found = searchBST(root, 10);
System.out.println(found.val);
// New node if root is null.
Node node = insertIntoBST(root, 20);
System.out.println(node.val);
}
}