What is the problem of my code?[java]


  • 0
    L
    public boolean isBalanced(TreeNode root) {
        if(root == null)
            return true;
        if(depth(root) != -1)
            return true;
        else return false;
    }
    
    public int depth(TreeNode root) {
        if(root == null)
            return 0;
        int leftdepth = depth(root.left)+1;;
        int rightdepth = depth(root.right)+1;;
        if(leftdepth == -1 || rightdepth == -1 || (Math.abs(leftdepth - rightdepth) > 1))
            return -1;
        else
            return Math.max(leftdepth,rightdepth);
    }
    

    My general idea is to calculate the depth of every node. If any subtree is unbalanced, the tree is ubalanced. The test case :[1,2,2,3,null,null,3,4,null,null,4] failed, and I have no I idea how this tree is constructed. Would you tell me what goes wrong in my algorithm?


  • -1
    M

    return Math.max(leftdepth,rightdepth) ,you should add 1, return Math.max(leftdepth,rightdepth)+1;


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.