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.
Example 1:
Given the following tree [3,9,20,null,null,15,7]
:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]
:
1
/ \
2 2
/ \
3 3
/ \
4 4
解题思路
本题要求判断平衡二叉树, 满足的条件就是任意结点的高度之差的绝对值是小于等于1,根据之前书上讲的定义| BF| <= 1(Balanced Factor) 平衡因子的值满足此要求。 对每个结点求高度判断即可(求高度原型104题),那就又是dfs了 一个dfs用来计算当前结点的高度,另一个用来判读平衡二叉树的条件。
解题代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
//判断是否是平衡二叉树
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
//平衡二叉树是通过判断每个结点之间的高度相差1;
int left = getHight(root.left);
int right = getHight(root.right);
//平衡二叉树的条件
return Math.abs(left - right) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
//计算当前结点的高度
public int getHight(TreeNode root){
if (root == null) return 0;
return Math.max(getHight(root.left), getHight(root.right)) + 1;
}
}