-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTree.java
115 lines (80 loc) · 2.34 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
public class BinaryTree {
Node root;
public void addNode(int key, String name){
Node newNode = new Node(key,name);
if(root == null){
root = newNode;
}
else{
Node focusNode = root;
Node parent;
while(true){
parent = focusNode;
if(key< focusNode.key){
focusNode = focusNode.leftChild;
if (focusNode == null){
parent.leftChild = newNode;
return;
}
}
else{
focusNode = focusNode.rightChild;
if (focusNode == null){
parent.rightChild = newNode;
return;
}
}
}
}
}
public void inOrderTraversal(Node focusNode){
if (focusNode != null){
inOrderTraversal(focusNode.leftChild);
System.out.println(focusNode);
inOrderTraversal(focusNode.rightChild);
}
}
public void preOrderTraversal(Node focusNode){
if (focusNode != null){
System.out.println(focusNode);
preOrderTraversal(focusNode.leftChild);
preOrderTraversal(focusNode.rightChild);
}
}
public void postOrderTraversal(Node focusNode){
if (focusNode != null){
postOrderTraversal(focusNode.leftChild);
postOrderTraversal(focusNode.rightChild);
System.out.println(focusNode);
}
}
public Node findNode(int key){
System.out.println("Searching for " + key);
Node focusNode = root;
while (focusNode.key != key){
if (key<focusNode.key){
focusNode=focusNode.leftChild;
}
else{
focusNode=focusNode.rightChild;
}
}
if (focusNode == null){
return null;
}
return focusNode;
}
public class Node{
int key;
String name;
Node leftChild;
Node rightChild;
Node(int key,String name){
this.key = key;
this.name = name;
}
public String toString(){
return name + " has a key " + key;
}
}
}