leetcode Balanced Binary Tree

来源:互联网 发布:js replace all 编辑:程序博客网 时间:2024/06/06 03:16
public class Solution {
    boolean flag=true;
    public boolean isBalanced(TreeNode root) {
        if(root==null)
            return true;
        dep(root);
        return flag;
    }
    public int dep(TreeNode root){
        int ldep,rdep;
        if(root==null)
            return 0;
        ldep=dep(root.left);
        rdep=dep(root.right);
        if(Math.abs(ldep-rdep)>1)
            flag=false;
        return Math.max(ldep,rdep)+1;    
    }

}

还没有搞清楚 递归之间的传参,以及返回顺序。

程序就算判断到子树不为平衡树,也无法立即返回。也要遍历完整树。

想起来 可以在dep函数里面通过flag判断接下来的判断要不要走下去。

public int dep(TreeNode root){
        int ldep,rdep;
        if(root==null  ||  !flag)
            return 0;
        ldep=dep(root.left);
        rdep=dep(root.right);
        if(Math.abs(ldep-rdep)>1)
            flag=false;
        return Math.max(ldep,rdep)+1;    
    }

0 0