VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-path-between-lowest-and-highest-value-in-a-binary-tree/

⇱ Find path between lowest and highest value in a Binary tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find path between lowest and highest value in a Binary tree

Last Updated : 31 Oct, 2023

Given a binary tree consisting of N nodes. Find the path between the node having the lowest value to the node having the highest value. There is no restriction on the traversal, i.e. the tree can be traversed upward, bottom, left and right.

Examples:

Input: N = 8

            2
         /     \
      1        6
    /   \         \   
  4   21        26
  /       \
5        7

{(2), (1, 6), (4, 21), (26), (5), (7)}
Output: 1 -> 2 -> 6 -> 26 
Explanation: The minimum value in the tree is 1, while the maximum value is 26. So the path from the minimum value, i.e. 1 to the maximum value, i.e. 26 is 1 -> 2 -> 6 -> 26. Other than that, there is no other path from the node consisting of the minimum value to the node consisting of the maximum value.

Input: N = 5

       10
      /  \
     5    20
         /  \
        17  25

{(10), (5, 20), (), (17, 25)}
Output: 5 -> 10 -> 20 -> 25
Explanation: The lowest node is 5 and the highest node is 25. The path between these two nodes is [5, 10, 20, 25].

Approach: This can be solved with the following idea:

  • The first intuition that builds up in minds is to traverse the entire binary tree and find the node with the lowest and highest values. 
  • Then find the lowest common ancestor of the nodes with the lowest and highest values, then print the paths from the lowest node to the highest node using the parent pointers. 
  • We start at the highest value node and follow its parent pointers until we reach the lowest common ancestor. Then, we print the lowest common ancestor and follow the parent pointers of the lowest value node until we reach the next lowest common ancestor. 

Below are the steps involved in the implementation of the code:

  • The program below defines a TreeNode struct to represent a node in the binary tree.
  • The findPath function takes the root node of the binary tree as input and finds the node with the lowest value and the node with the highest value by performing a breadth-first search of the tree.
  • Then, the function traverses up from the lowest value node and the highest value node to find their common ancestor node. 
  • Finally, the function prints the path from the lowest value node to the common ancestor node and the path from the common ancestor node to the highest value node.

Output
1 2 6 26 

Time Complexity: O(N) 
Auxiliary Space: O(h)

Comment
Article Tags: