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?