Skip to content
Related Articles

Related Articles

Length of longest straight path from a given Binary Tree

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 21 Jun, 2021
View Discussion
Improve Article
Save Article

Given a Binary Tree, the task is to find the length of the longest straight path of the given binary tree.

Straight Path is defined as the path that starts from any node and ends at another node in the tree such that the direction of traversal from the source node to the destination node always remains the same i.e., either left or right, without any change in direction that is left->left ->left or right->right->right direction. 

Examples:

Input:

Output: 2
Explanation:
The path shown in green is the longest straight path from 4 to 6 which is of length 2. 
 

Input:

Output: 3
Explanation:
The path shown in green is the longest straight path from 5 to 0 which is of length 3. 
 

Approach: The idea is to use the Postorder traversal. Follow the steps below to solve the problem:

  1. For each node, check the direction of the current Node (either left or right) and check which direction of its child is providing the longest length below it to that node.
  2. If the direction of the current node and the child giving the longest length is not the same then save the result of that child and pass the length of the other child to its parent.
  3. Using the above steps find the longest straight path at each node and save the result to print the maximum value among all the straight paths.
  4. Print the maximum path after the above steps.

Below is the implementation of the above approach:

Code block

Output: 

2

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!