-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBuildBST.java
46 lines (39 loc) · 1.02 KB
/
BuildBST.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
public class BuildBST {
public static class Node {
int data;
Node left;
Node right;
public Node(int data){
this.data = data;
this.left = this.right = null;
}
}
public static Node buildBST(Node root, int val){
if(root == null){
root = new Node(val);
return root;
}
if(root.data > val){
root.left = buildBST(root.left, val);
} else {
root.right = buildBST(root.right, val);
}
return root;
}
public static void inorderTraversal(Node root){
if(root == null){
return;
}
inorderTraversal(root.left);
System.out.print(root.data+" ");
inorderTraversal(root.right);
}
public static void main(String[] args) {
int arr[] = {5,1,3,4,2,7};
Node root = null;
for(int i=0; i<arr.length; i++){
root = buildBST(root, arr[i]);
}
inorderTraversal(root);
}
}