0

I'm working on this leetcode problem:

https://leetcode.com/problems/maximum-depth-of-binary-tree/

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Working Code:

public class Solution {
    public int maxDepth(TreeNode root) {

        if(root == null)
            return 0;

        int left = maxDepth(root.left);
        int right = maxDepth(root.right);

        if(left > right)
            return left + 1;
        else
            return right + 1;
    }
}

Non-working Code:

public class Solution {
    int left = 0;
    int right = 0;
    public int maxDepth(TreeNode root) {

        if(root == null)
            return 0;

        left = maxDepth(root.left);
        right = maxDepth(root.right);

        if(left > right)
            return left + 1;
        else
            return right + 1;
    }
}

Could someone explain why one doesn't work? Recursion hurts my head.

Ling Zhong
  • 1,744
  • 14
  • 24
caker
  • 178
  • 2
  • 14

1 Answers1

4

In the first example, which you've said works, left and right are local variables within maxDepth, and so each call to maxDepth has its own private copy of them that other calls to maxDepth cannot change.

In the second example, left and right are instance fields, and so all calls to maxDepth on that instance will share them. Consequently, when maxDepth calls itsself, it overwrites the values in left and right from any containing call. E.g., here:

left = maxDepth(root.left);
right = maxDepth(root.right);

...the first call returns a value for left, which is then overwritten by the second call, because the second call also does left = maxDepth(root.left);. Additionally, if you end up recursing further (as you probably will), both left and right are overwritten.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875