As mentioned in another answer , the reason your visit request is โ "reverse" is because you use Stack to track the "current node".
Let me guide you through your example tree:
0 / \ 6 7 / \ / \ 5 4 3 2
stack.push(root) results in the following state of the stack:
0: 0 <-- (root) and Top of stack
You pop the stack and put it in curr . In terms of passing, you are in this state:
0 <-- / \ 6 7 / \ / \ 5 4 3 2
then go on to add curr.getLeft() to the stack and then curr.getRight() . This leads to the following state of the stack:
1: 7 <--(curr.getRight()) <-- Top of stack 0: 6 <--(curr.getLeft())
Repeating the same step, we get the following workaround:
0 / \ 6 7<-- / \ / \ 5 4 3 2
and after adding nodes:
2: 2 <-- Top of stack 1: 3 0: 6 <-- (initial getLeft())
since both nodes have no children, pushing them out of the stack, and outputting them leads us to the following workaround:
0 / \ -->6 7 / \ / \ 5 4 3 2
The rest is history;)
As you specifically asked about the โrightโ way (or order) for DFS: it is not. You determine which side you go first in depth.
Vogel612
source share