题目:
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.
翻译:
给定一个二叉树,检测它是否是高度平衡的。
这个问题中,一个高度平衡的二叉树是定义在一个二叉树上,它的每个节点的两棵子树的高度相差都不超过1。
分析:
这其实就是判断是否是平衡二叉树。
平衡二叉树,又称AVL树。它或者是一棵空树,或者是具有下列性质的二叉树:它的左子树和右子树都是平衡二叉树,且左子树和右子树的高度之差之差的绝对值不超过1。
下面的做法,递归遍历每个节点,每次递归,都获取左右子树的高度进行判断,采用-1作为已经检测到不平衡的标志位,其余情况返回当前子树的高度,用作上一层递归判断。
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
int depth=getDepth(root,0);
return depth!=-1;//-1代表子树出现不平衡
}
public int getDepth(TreeNode root,int length){
if(root==null){
return length;
}
int leftDepth=getDepth(root.left,length+1);
int rightDepth=getDepth(root.right,length+1);
if(leftDepth==-1||rightDepth==-1||leftDepth-rightDepth>1||rightDepth-leftDepth>1){
return -1;
}
return leftDepth>rightDepth?leftDepth:rightDepth;
}
}