-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTree.java
More file actions
72 lines (57 loc) · 1.56 KB
/
BinaryTree.java
File metadata and controls
72 lines (57 loc) · 1.56 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
public class BinaryTree<E> {
private BinaryTree<E> left, right;
private E data;
public BinaryTree(E data) {
this.data = data;
this.left = null;
this.right = null;
}
public BinaryTree(E data, BinaryTree<E> left, BinaryTree<E> right) {
this.data = data;
this.left = left;
this.right = right;
}
public boolean isLeaf() {
return left == null && right == null;
}
public boolean isInternal() {
return left != null || right != null;
}
public boolean hasLeftChild() {
return left != null;
}
public boolean hasRightChild() {
return right != null;
}
public BinaryTree<E> getLeft() {
return left;
}
public BinaryTree<E> getRight() {
return right;
}
public E getData() {
return data;
}
public int count() {
BinaryTree<E> left = getLeft();
BinaryTree<E> right = getRight();
return 1 + (left != null ? left.count() : 0) + (right != null ? right.count() : 0);
}
public int countLeaves() {
if (this.isLeaf() == true) {
return 1;
}
BinaryTree<E> left = getLeft();
BinaryTree<E> right = getRight();
return (left != null ? left.countLeaves() : 0) + (right != null ? right.countLeaves() : 0);
}
public void setData(E data) {
this.data = data;
}
public void setLeft(BinaryTree<E> left) {
this.left = left;
}
public void setRight(BinaryTree<E> right) {
this.right = right;
}
}