[剑指offer]平衡二叉树

在这里插入图片描述
思路:
遍历每个节点,借助一个获取树深度的递归函数,根据该节点的左右子树高度差判断是否平衡,然后递归地对左右子树进行判断。
实现:

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        return getDept(root) != -1;
    }
    private int getDept(TreeNode root){
        if(root == null) return 0;
        int left = getDept(root.left);
        if(left == -1) return -1;
        int right = getDept(root.right);
        if(right == -1) return -1;
        return Math.abs(left - right) > 1 ? -1 : 1 + Math.max(left , right);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37344518/article/details/84976778