-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathBinaryTree.java
More file actions
137 lines (111 loc) · 2.62 KB
/
BinaryTree.java
File metadata and controls
137 lines (111 loc) · 2.62 KB
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package algorithm.basic;
import java.util.LinkedList;
import java.util.Queue;
/**
* The basic operations of binary tree.
*
* @param <T> The comparable element in tree.
*/
public class BinaryTree<T extends Comparable<T>> {
private TreeNode<T> root;
public BinaryTree() {
this.root = null;
}
public void setRoot(TreeNode<T> root) {
this.root = root;
}
public void preorder() {
preorder(root);
}
private void preorder(TreeNode<T> node) {
if(node != null) {
System.out.println(node.value);
preorder(node.left);
preorder(node.right);
}
}
public void inorder() {
inorder(root);
}
private void inorder(TreeNode<T> node) {
if(node != null) {
inorder(node.left);
System.out.println(node.value);
inorder(node.right);
}
}
public void postorder() {
postorder(root);
}
private void postorder(TreeNode<T> node) {
if(node != null) {
postorder(node.left);
postorder(node.right);
System.out.println(node.value);
}
}
public int height() {
return height(root);
}
private int height(TreeNode<T> node) {
if(node == null) {
return 0;
}
return 1 + Math.max(height(node.left), height(node.right));
}
public int size() {
return size(root);
}
private int size(TreeNode<T> node) {
if(node == null) {
return 0;
}
return 1 + size(node.left) + size(node.right);
}
public void breathFirstTraversal() {
Queue<TreeNode<T>> queue = new LinkedList<>();
queue.add(root);
while(queue.isEmpty() == false) {
TreeNode<T> node = queue.poll();
if(node != null) {
System.out.println(node.value);
if(node.left != null) {
queue.add(node.left);
}
if(node.right != null) {
queue.add(node.right);
}
}
}
}
public int diameter() {
return diameter(root);
}
private int diameter(TreeNode<T> node) {
if(node == null) {
return 0;
}
int lHeight = height(node.left);
int rHeight = height(node.right);
return Math.max(lHeight + rHeight + 1, Math.max(diameter(node.left), diameter(node.right)));
}
public static class TreeNode<T> {
T value;
TreeNode<T> left;
TreeNode<T> right;
public TreeNode(T value) {
this(value, null, null);
}
public TreeNode(T value, TreeNode<T> left, TreeNode<T> right) {
this.value = value;
this.left = left;
this.right = right;
}
public void setLeft(TreeNode<T> left) {
this.left = left;
}
public void setRight(TreeNode<T> right) {
this.right = right;
}
}
}