-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBalancedTree.java
More file actions
35 lines (30 loc) · 1.04 KB
/
BalancedTree.java
File metadata and controls
35 lines (30 loc) · 1.04 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
package swe.Tree;
public class BalancedTree {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
int leftHeight = getHeight(root.left);
int rightHeight = getHeight(root.right);
if (Math.abs(leftHeight - rightHeight) > 1) {
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
}
private int getHeight(TreeNode node) {
if (node == null) {
return 0;
}
return Math.max(getHeight(node.left), getHeight(node.right) + 1);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.right.left = new TreeNode(4);
root.right.right = new TreeNode(5);
root.right.right.right = new TreeNode(7);
BalancedTree bt = new BalancedTree();
System.out.println(bt.isBalanced(root)); // false
}
}