-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTreeNode.java
116 lines (99 loc) · 2.51 KB
/
TreeNode.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
116
public class TreeNode {
private Integer data;
private TreeNode leftChild;
private TreeNode rightChild;
public TreeNode(Integer data) {
this.data = data;
}
public static TreeNode addSorted(int[] data, int start, int end) {
if (end >= start) {
int mid = (start+end)/2;
TreeNode newNode = new TreeNode(data[mid]);
newNode.leftChild = addSorted(data, start, mid-1);
newNode.rightChild = addSorted(data, mid+1, end);
return newNode;
}
return null;
}
public int height() {
if (isLeaf()) return 1;
int left = 0;
int right = 0;
if (this.leftChild != null)
left = this.leftChild.height();
if (this.rightChild != null)
right = this.rightChild.height();
return (left > right) ? (left + 1) : (right + 1);
}
public int numOfLeafNodes() {
if (isLeaf()) return 1;
int leftLeaves = 0;
int rightLeaves = 0;
if (this.leftChild != null)
leftLeaves = leftChild.numOfLeafNodes();
if (this.rightChild != null)
rightLeaves = rightChild.numOfLeafNodes();
return leftLeaves + rightLeaves;
}
public boolean isLeaf() {
return this.leftChild == null && this.rightChild == null;
}
public void traverseInOrder() {
if (this.leftChild != null)
this.leftChild.traverseInOrder();
System.out.print(this + " ");
if (this.rightChild != null)
this.rightChild.traverseInOrder();
}
public TreeNode find(Integer data) {
if (this.data == data)
return this;
if (data < this.data && leftChild != null)
return leftChild.find(data);
if (rightChild != null)
return rightChild.find(data);
return null;
}
public void insert(Integer data) {
if (data >= this.data) { // insert in right subtree
if (this.rightChild == null)
this.rightChild = new TreeNode(data);
else
this.rightChild.insert(data);
} else { // insert in left subtree
if (this.leftChild == null)
this.leftChild = new TreeNode(data);
else
this.leftChild.insert(data);
}
}
public Integer largest() {
if (this.rightChild == null)
return this.data;
return this.rightChild.largest();
}
public Integer smallest() {
if (this.leftChild == null)
return this.data;
return this.leftChild.smallest();
}
public Integer getData() {
return data;
}
public TreeNode getLeftChild() {
return leftChild;
}
public void setLeftChild(TreeNode left) {
this.leftChild = left;
}
public TreeNode getRightChild() {
return rightChild;
}
public void setRightChild(TreeNode right) {
this.rightChild = right;
}
@Override
public String toString() {
return String.valueOf(this.data);
}
}