【LintCode-93】平衡二叉树(Java实现-递归算法)

《【LintCode-93】平衡二叉树(Java实现-递归算法)》
第一次代码记录:

    public boolean isBalanced(TreeNode root) {
        if(root==null||(root.left==null&&root.right==null)){
            return true;
        }
        if(root.left!=null&&root.right!=null){
            return isBalanced(root.left)&&isBalanced(root.right);
        }else if(root.left!=null){
            return depth(root.left)>1?false:true;
        }else{
            return depth(root.right)>1?false:true;
        }
        // write your code here
    }
    public int depth(TreeNode root){
        if(root==null){
            return 0;
        }
        int leftRootDepth=depth(root.left);
        int    rightRootDepth=depth(root.right);
        return (leftRootDepth>rightRootDepth?leftRootDepth:rightRootDepth)+1;
    }

LintCode测试BUG指出:
在LintCode提交测试,显示正常通过,但其实是不全对,因为代码里只判断了单独的左右子树是否平衡(return isBalanced(root.left)&&isBalanced(root.right);),而没有判断当前这个节点,左右子树的高度差是否满足小于等于1的平衡条件。测试数据:{1,2,3,4,5,#,#,6,7,8,9,#,#,#,#} 根节点左右子树不平衡。

第二次代码记录:

    public boolean isBalanced(TreeNode root) {
        if(root==null){
            return true;
        }
        int depthRootLeft=depth(root.left);
        int depthRootRight=depth(root.right);
        if(Math.abs(depthRootLeft-depthRootRight)<=1){
            return isBalanced(root.left)&&isBalanced(root.right);
        }
        return false;
    }
    public int depth(TreeNode root){
        if(root==null){
            return 0;
        }
        int depthLeft=depth(root.left);
        int depthRight=depth(root.right);
        return (depthLeft>depthRight?depthLeft:depthRight)+1;//取左右子树最大值+1;
    }  

个人解题思路:
判断当前这个二叉树是否平衡,其实就是判断这个二叉树上的没有treeNode节点是否平衡。
1.我们需要先求出这个左右子树的高度(通过depth()),depth()里用了递归算法求出其参数root节点的左右子树高度,并取其最大值+1。
2.回来isBalanced()里,取到左右子树高度后,进行判断当前节点是否平衡,如果平衡就继续递归其左右子树节点是否平衡,并将两者结果用且(&&)返回。

如果您有更好的解法,欢迎您在留言区补充,感谢!!

    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/yangdongchuan1995/article/details/78453665
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞