0ms--java--less space---use LRD


  • 0
    S
    private static int max ;
    private static int curDepth ;
    
    public static int maxDepth(TreeNode root) {
        max =0;
        curDepth = 0;
        calDepth(root);
        return max;
    }
    
    private static void calDepth(TreeNode treeNode) {
    
        if (treeNode == null) {
            return;
        }
        curDepth++;
        if (curDepth > max) {
            max = curDepth;
        }
        calDepth(treeNode.left);
        calDepth(treeNode.right);
        curDepth--;
    }

  • 0
    F

    I ‘m puzzled about the initialization of the static variables max and curdepth, I've tried to run this code, and I found that when I initialized the two variables in the beginning instead of inside the method, it turned out that the answer was wrong, and I couldn't tell why.I would be so appreciated if someone can tell me why.


  • 0
    S

    maybe their code look like this:

    public class MaxDepthOfTrees {

    private static int max;
    private static int curDepth;
    
    
    public void testFunc() {
    
        assert (2 == maxDepth(rootNode2));
        assert (3 == maxDepth(rootNode3)); 
    }
    
    public static int maxDepth(TreeNode root) {
        max = 0;
        curDepth = 0;
        calDepth(root);
        return max;
    }
    

    }

    so. you have to reset the var.
    just likeJunit -> setUp & TearDown


Log in to reply
 

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