Star

LeetCode 110. Balanced Binary Tree

Question

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Explanation

在这里还是用递归,判断条件为1. 左右子树均balance 2.左右子树高度只差不超过1. 所以在这道题中,为了能返回两个值,就创建了一个新的类:ResultType。如果用python写就不用了。

Code

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class ResultType {
public boolean isBalanced;
public int maxDepth;
public ResultType(boolean isBalanced, int maxDepth) {
this.isBalanced = isBalanced;
this.maxDepth = maxDepth;
}
}
public class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
return helper(root).isBalanced;
}
public ResultType helper(TreeNode root) {
if (root == null ) return new ResultType(true, 0);
ResultType left = helper(root.left);
ResultType right = helper(root.right);
if (left.isBalanced && right.isBalanced && Math.abs(left.maxDepth-right.maxDepth)<=1) {
return new ResultType(true, Math.max(left.maxDepth,right.maxDepth)+1);
}
return new ResultType(false, -1);
}
}