![]() |
VOOZH | about |
Given a tree and node data, the task to reverse the path to that particular Node.
Examples:
Input: 7 / \ 6 5 / \ / \ 4 3 2 1 Data = 4 Output: Inorder of tree 7 6 3 4 2 5 1 Input: 7 / \ 6 5 / \ / \ 4 3 2 1 Data = 2 Output : Inorder of tree 4 6 3 2 7 5 1
The idea is to use a map to store path level wise.
Find the Node path as well as store it in the map
the path is
Replace the position with the map nextPos index value
increment the nextpos index and replace the next value
increment the nextpos index and replace the next value
Implementation:
7 6 3 4 2 5 1
Complexity Analysis:
Another Approach:
Use the concept of printing all the root-to-leaf paths. The idea is to keep a track of the path from the root to that particular node upto which the path is to be reversed and once we get that particular node we simply reverse the data of those nodes.
Here we will not only try to track all the root the leaf paths but also check for the node up to which we need to reverse the path.
Use a vector to store every path.
Once we get the node up to which the path needs to be reversed we use a simple algorithm to reverse the data of the nodes found in the followed path that is store in the vector.
Implementation of the above approach given below:
7 6 3 4 2 5 1
Complexity Analysis: