要判断一棵树是否为平衡二叉树,二叉树每个节点的高度差不能相差超过1.
可以定义一个height函数,height§=0,p 是空节点。
height§=max(height(p.left),height(p.right))+1,p 是非空节点。
具体做法类似于二叉树的前序遍历,即对于当前遍历到的节点,首先计算左右子树的高度,如果左右子树的高度差是否不超过 111,再分别递归地遍历左右子节点,并判断左子树和右子树是否平衡。这是一个自顶向下的递归的过程。
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null){
return true;
}else{
return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
}
public int height(TreeNode root){
if(root == null){
return 0;
}else{
return Math.max(height(root.left), height(root.right)) + 1;
}
}
}