描述
给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:
一棵二叉树中每个节点的两个子树的深度相差不会超过1。
样例
给出二叉树 A={3,9,20,#,#,15,7}, B={3,#,20,15,7}
A) 3 B) 3
/ \ \
9 20 20
/ \ / \
15 7 15 7
二叉树A是高度平衡的二叉树,但是B不是
思路
定义一个ResultType类型返回isBalanced 和 maxDepth(深度用于判断高度差是否相差1)
二叉树不平衡的条件:
a.左右子树存在一个不平衡
b.左右子树的深度相差超过一
代码
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
- with ResultType
class ResultType {
public boolean isBalanced;
public int maxDepth;
public ResultType(boolean isBalanced, int maxDepth) {
this.isBalanced = isBalanced;
this.maxDepth = maxDepth;
}
}
public class Solution {
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
public boolean isBalanced(TreeNode root) {
return helper(root).isBalanced;
}
private ResultType helper(TreeNode root) {
if (root == null) {
return new ResultType(true, 0);
}
ResultType left = helper(root.left);
ResultType right = helper(root.right);
// subtree not balance
// 此处关键在于false,后面的数字是多少其实都用不上
if (!left.isBalanced || !right.isBalanced) {
return new ResultType(false, -1);
}
// root not balance
if (Math.abs(left.maxDepth - right.maxDepth) > 1) {
return new ResultType(false, -1);
}
// 左右子树高度最大值+1就是根结点高度
return new ResultType(true, Math.max(left.maxDepth, right.maxDepth) + 1);
}
}