-
Notifications
You must be signed in to change notification settings - Fork 1
/
TreeNode.java
118 lines (97 loc) · 2.58 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
117
118
package data_structures.trees;
public class TreeNode {
private double data;
private TreeNode leftChild;
private TreeNode rightChild;
public TreeNode(double data) {
this.data = data;
}
public TreeNode get(double value) {
if (value == data) {
return this;
}
if (value < data) {
if (leftChild != null) return leftChild.get(value);
} else {
if (rightChild != null) return rightChild.get(value);
}
return null;
}
public void insert(double value) {
if (value == data) return; //no duplicates
if (value < data) {
if (leftChild == null) {
leftChild = new TreeNode(value);
} else {
leftChild.insert(value);
}
} else {
if (rightChild == null) {
rightChild = new TreeNode(value);
} else {
rightChild.insert(value);
}
}
}
public void traversePreOrder() {
System.out.print(data + ", ");
if (leftChild != null) {
leftChild.traversePreOrder();
}
if (rightChild != null) {
rightChild.traversePreOrder();
}
}
public void traverseInOrder() {
if (leftChild != null) {
leftChild.traverseInOrder();
}
System.out.print(data + ", ");
if (rightChild != null) {
rightChild.traverseInOrder();
}
}
public void traversePostOrder() {
if (leftChild != null) {
leftChild.traversePostOrder();
}
if (rightChild != null) {
rightChild.traversePostOrder();
}
System.out.print(data + ", ");
}
public double min() {
if (leftChild != null) {
return leftChild.min();
} else return data;
}
public double max() {
if (rightChild != null) {
return rightChild.max();
} else return data;
}
public double getData() {
return data;
}
public void setData(double data) {
this.data = data;
}
public TreeNode getLeftChild() {
return leftChild;
}
public void setLeftChild(TreeNode leftChild) {
this.leftChild = leftChild;
}
public TreeNode getRightChild() {
return rightChild;
}
public void setRightChild(TreeNode rightChild) {
this.rightChild = rightChild;
}
@Override
public String toString() {
return "TreeNode{" +
"data=" + data +
'}';
}
}