-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_110.java
More file actions
31 lines (25 loc) · 792 Bytes
/
Copy pathP_110.java
File metadata and controls
31 lines (25 loc) · 792 Bytes
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
package leetcode.easy;
import utils.DataStructures.TreeNode;
public class P_110 {
private static class Pair {
int d;
boolean isBalanced;
Pair(int d, boolean isBalanced) {
this.d = d;
this.isBalanced = isBalanced;
}
}
public boolean isBalanced(TreeNode root) {
return dfs(root).isBalanced;
}
private static Pair dfs(TreeNode node) {
if (node == null) {
return new Pair(0, true);
}
final Pair left = dfs(node.left);
final Pair right = dfs(node.right);
final int d = 1 + Math.max(left.d, right.d);
final boolean isBalanced = Math.abs(left.d - right.d) <= 1 && left.isBalanced && right.isBalanced;
return new Pair(d, isBalanced);
}
}