Skip to content

Commit e3ee20a

Browse files
committed
tree example
1 parent 2be14c8 commit e3ee20a

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Diff for: class-38/Tree.java

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import java.util.*;
2+
3+
public class Tree {
4+
int value;
5+
Tree left;
6+
Tree right;
7+
8+
public Tree() {}
9+
public Tree(int value) {
10+
this.value = value;
11+
}
12+
13+
public Tree(int value, Tree left, Tree right) {
14+
this.value = value;
15+
this.left = left;
16+
this.right = right;
17+
}
18+
19+
public static void main(String[] args) {
20+
Tree t = new Tree(1, new Tree(2, new Tree(1), new Tree(1)), new Tree(3, new Tree(1), new Tree(1)));
21+
System.out.println(isBalanced(t));
22+
Tree unbalanced = new Tree(1, new Tree(1, new Tree(1), null), null);
23+
System.out.println(isBalanced(unbalanced));
24+
}
25+
26+
public static boolean isBalanced(Tree input) {
27+
if (input == null) {
28+
return true;
29+
}
30+
else {
31+
return isBalanced(input.left) &&
32+
isBalanced(input.right) &&
33+
Math.abs(height(input.left) - height(input.right)) < 2;
34+
}
35+
}
36+
37+
public static int height(Tree input) {
38+
if (input == null) return 0;
39+
return 1 + Math.max(height(input.left), height(input.right));
40+
}
41+
}

0 commit comments

Comments
 (0)