Skip to content
Related Articles

Related Articles

Improve Article

Length of longest straight path from a given Binary Tree

  • Difficulty Level : Medium
  • Last Updated : 21 Jun, 2021

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)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up
Recommended Articles
Page :