/
_0110_BalancedBinaryTree.java
49 lines (42 loc) · 1.55 KB
/
_0110_BalancedBinaryTree.java
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
package com.diguage.algorithm.leetcode;
import com.diguage.algorithm.util.TreeNode;
import java.util.Objects;
import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;
import static java.util.Arrays.asList;
/**
* = 110. Balanced Binary Tree
*
* https://leetcode.com/problems/balanced-binary-tree/[LeetCode - Balanced Binary Tree]
*
* @author D瓜哥, https://www.diguage.com/
* @since 2020-02-06 23:10
*/
public class _0110_BalancedBinaryTree {
/**
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Balanced Binary Tree.
* Memory Usage: 41.4 MB, less than 11.11% of Java online submissions for Balanced Binary Tree.
*/
public boolean isBalanced(TreeNode root) {
return depth(root) != -1;
}
private int depth(TreeNode root) {
if (Objects.isNull(root)) {
return 0;
}
int left = depth(root.left);
if (left == -1) {
return -1;
}
int right = depth(root.right);
if (right == -1) {
return -1;
}
return Math.abs(left - right) < 2 ? Math.max(left, right) + 1 : -1;
}
public static void main(String[] args) {
_0110_BalancedBinaryTree solution = new _0110_BalancedBinaryTree();
System.out.println(!solution.isBalanced(buildTree(asList(1, 2, 2, 3, null, null, 3, 4, null, null, 4))));
System.out.println(solution.isBalanced(buildTree(asList(3, 9, 20, null, null, 15, 7))));
System.out.println(!solution.isBalanced(buildTree(asList(1, 2, 2, 3, 3, null, null, 4, 4))));
}
}