剑指offer-39-2.平衡二叉树

https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=13&tqId=11192&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。

题解:
在求二叉树深度的基础上修改
中序遍历,从低向上,如果左右子树深度差大于1 ,直接返回,-1 是一个标记,说明不满足平衡条件。

public class Solution {
   public boolean IsBalanced_Solution(TreeNode root) {
        return TreeDepth(root) != -1;
    }
    public int TreeDepth(TreeNode root) {
        if(root==null){
            return 0;
        }
        int left=TreeDepth(root.left);
        if(left==-1){//剪枝
            return -1;
        }
        int right=TreeDepth(root.right);
        if(right==-1){//剪枝
            return -1;
        }
        if(Math.abs(left-right)>1){
            return -1;
        }
        return 1+(left>right?left:right);
    }
}

猜你喜欢

转载自blog.csdn.net/zxm1306192988/article/details/81232864