Input {2,1,3} output "true" in eclipse but submit solution on leetcode output false


  • 1
    C
    public class Solution {
    static boolean balanced = true;
    public boolean isBalanced(TreeNode root) {
        int rightDepth = 0;
        int leftDepth = 0;
    
        if (root == null)
            return true;
    
        ChildNodeDepth(root);
    
        return balanced;
    }
    
    public int ChildNodeDepth(TreeNode root){
        int rightDepth = 0;
        int leftDepth = 0;
        
        if (root == null) return 0;
        if (!balanced) return 0;
                
        rightDepth = ChildNodeDepth(root.right) + 1;
        leftDepth = ChildNodeDepth(root.left) + 1;
        
        
        balanced = Math.abs(rightDepth - leftDepth) > 1 ? false : true;
    
        return rightDepth > leftDepth ? rightDepth : leftDepth;
    }

  • 0
    D

    No doubt you've figured it out but for anyone just doing this question now and having similar results... the below hint may be a bit of a spoiler:

    The online judge does not create a new instance of the 'application' your code is part of for each test (your methods are just called repeatedly). I'm doing the questions in JavaScript but I suspect the same is true for other languages.


Log in to reply
 

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