VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-tree-path/

⇱ Reverse tree path - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reverse tree path

Last Updated : 11 Jul, 2025

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.
 

👁 Image

Find the Node path as well as store it in the map
 

👁 Image


the path is 
 

👁 Image


Replace the position with the map nextPos index value 
 

👁 Image


increment the nextpos index and replace the next value 
 

👁 Image


increment the nextpos index and replace the next value 
 

👁 Image


Implementation:


Output
7 6 3 4 2 5 1 

Complexity Analysis:

  • Time Complexity: O(nlogn). Here n is the number of elements in the tree.
  • Auxiliary Space: O(n), The extra space is used to store the elements in the map and recursive function call stack which can go upto O(h), where h is the height of the tree.

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:


Output
7 6 3 4 2 5 1 

Complexity Analysis:

  • Time Complexity: O(N)
  • Space Complexity: O(N)
Comment
Article Tags: