Here is a simpler example.
Node1 root = new Node1(1);
root.left = new Node(2);
root.right = new Node(3);
With the expected result
[1,2]
[1,3]
And actual result
[1,2]
[1,2,3]
When you first call printRootToLeaf, List
is empty. You add 1 to it, and call printRootToLeaf
on the left branch. Within that call, you add 2 to the list, and print [1,2]
. You then return to the first call, but 2 is still in the list! You then call printRootToLeaf
on the right branch. Within that call, you add 3 to the list, and print [1,2,3]
.
Changes made to the list while recursing down the left branch shouldn't propogate to the list passed down the right branch. The easiest way to address this is to make copies of the list each time:
printRootToLeaf(root.left, copy(list));
printRootToLeaf(root.right, copy(list));
The actual method of copying the list will vary depending upon what language you're using.