This repository was archived by the owner on Apr 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathPopulateBST.java
88 lines (58 loc) · 2.08 KB
/
PopulateBST.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import java.util.LinkedList;
import java.util.Queue;
//-- POPULATING A BINARY SEARCH TREE!!
public class PopulateBST{
static class TreeNode{
TreeNode left,right;
int dValue;
TreeNode(int v){
dValue = v;
left = null;
right = null;
}
}
public static void levelOrderTraversal(TreeNode root){
Queue<TreeNode> nodeQueue = new LinkedList<>();
nodeQueue.add(root);
while(!nodeQueue.isEmpty()){
TreeNode currentNode = nodeQueue.poll();
if(currentNode.left!=null)
nodeQueue.add(currentNode.left);
if(currentNode.right!=null)
nodeQueue.add(currentNode.right);
System.out.println(currentNode.dValue);
}
}
//-- POPULATING THE BINARY SEARCH TREE USING THE METHOD populateBST
public static void populateBST(TreeNode root, TreeNode addNode){
if(addNode.dValue<root.dValue){
if(root.left==null)
root.left = addNode;
else
populateBST(root.left, addNode);
}
else if(addNode.dValue>root.dValue){
if(root.right==null)
root.right = addNode;
else
populateBST(root.right, addNode);
}
else{
//DO NOTHING
}
}
public static void main(String[] args){
TreeNode root = new TreeNode(50);
populateBST(root, new TreeNode(10));
populateBST(root, new TreeNode(20));
populateBST(root, new TreeNode(30));
populateBST(root, new TreeNode(40));
populateBST(root, new TreeNode(50));
populateBST(root, new TreeNode(60));
populateBST(root, new TreeNode(70));
populateBST(root, new TreeNode(80));
populateBST(root, new TreeNode(90));
//Level Order Traversal in the above Tree
levelOrderTraversal(root);
}
}