-1

I was solving this leetcode question https://leetcode.com/problems/binary-tree-right-side-view/description/ .

The following code works correctly.

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List <Integer> ans = new LinkedList<>();
        if (root == null) return ans;
        traverse(root, ans, 0);
        return ans;
    }

    public void traverse(TreeNode root, List<Integer> ans, int currDepth){
        if (root == null) return;

        if (ans.size() == currDepth) ans.add(root.val);
        traverse(root.right, ans, currDepth + 1);
        traverse(root.left, ans, currDepth + 1);
    }
}

However, during the last 2 recursive calls, if I change the lines to

 traverse(root.right, ans, ++currDepth);
 traverse(root.left, ans, ++currDepth);

the code fails, why does this happen? Shouldn't both versions be equivalent?

George Francis
  • 462
  • 2
  • 7
  • 16

1 Answers1

1

Let us say currDepth = 0

In your first version, the two recursive calls will look like this:

traverse(root.right, ans, 1);
traverse(root.left, ans, 1);

This is correct because you want both recursive calls to go to the next level.

In your second version, it looks like this:

traverse(root.right, ans, 1);
traverse(root.left, ans, 2);

This means the first recursive call works fine, but the second one is wrong (skips one level).

Why? you changed your currDepth parameter. The first version of your code doesn't change it. It passes currDepth + 1 to the next level.

borat
  • 126
  • 1
  • 3
  • 13