Length of longest straight path from a given Binary Tree
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.
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.
The path shown in green is the longest straight path from 4 to 6 which is of length 2.
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:
- 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.
- 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.
- 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.
- Print the maximum path after the above steps.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)