I am trying to find out how to get the path from root to a given node on a binary tree.
It is not binary search tree.
Each non-leaf node has only two pointers to their children.
In-order, pre-order, post-order traversal do not work.
I have tried to do pre-order but cannot figure out how. For example, we have a binary tree: It is NOT a binary search tree. We use the sorting order node to make it easier to find the path.
1
/ \
2 3
/ \ / \
4 5 6 7
We want to find the path from 1 to 7:
With pre-order, we have:
1 -> 2 -> 4 -> 5 -> 3 -> 6 -> 7
From the flow, we get the path from 1 -> 7 with all nodes on it.
Obviuosly, it should not be.
Any help is really appreciated.
Preorder traversal, otherwise known as depth-first search does work.
If you implement preorder traversal recursively, then when you reach the desired node, you can unwind your stack (of recursive calls) and construct your path in reverse.
If you implement the preorder traversal non-recursively, then you will be building a stack directly, so in this case once you reach your desired node you have your path already.
In the tree in your question above, the algorithm to find the path from 1 to 7 proceeds as follows.