-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTree.java
78 lines (57 loc) · 1.5 KB
/
BinaryTree.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
public class BinaryTree {
Node root;
public void addNode(int key, String name){
Node node = new Node(key, name);
if(root == null){
root = node;
} else {
Node tempNode = root;
Node parent;
while(true){
parent = tempNode;
if(node.key < tempNode.key){
tempNode = tempNode.leftChild;
if(tempNode == null){
parent.leftChild = node;
return;
}
} else {
tempNode = tempNode.rightChild;
if(tempNode == null){
parent.rightChild = node;
return;
}
}
}
}
}
public static void inorderTranverserTree(Node root){
if(root != null){
inorderTranverserTree(root.leftChild);
System.out.println(root.key + " " + root.name);
inorderTranverserTree(root.rightChild);
}
}
public static void main(String args[]) {
BinaryTree tree = new BinaryTree();
tree.addNode(50, "Steven");
tree.addNode(10, "Steven1");
tree.addNode(30, "Steven2");
tree.addNode(32, "Steven3");
tree.addNode(5, "Steven4");
tree.addNode(58, "Steven5");
tree.addNode(149, "Steven6");
tree.addNode(17, "Steven7");
inorderTranverserTree(tree.root);
}
}
class Node {
int key;
String name;
Node leftChild;
Node rightChild;
public Node(int key, String name) {
this.key = key;
this.name = name;
}
}