Given a binary tree, find the path length having maximum number of bends.
Note : Here, bend indicates switching from left to right or vice versa while traversing in the tree.
For example, consider below paths (L means moving leftwards, R means moving rightwards):
LLRRRR – 1 Bend
RLLLRR – 2 Bends
LRLRLR – 5 Bends
Prerequisite : Finding Max path length in a Binary Tree
Input : 4 / \ 2 6 / \ / \ 1 3 5 7 / 9 / \ 12 10 \ 11 / \ 45 13 \ 14 Output : 6 In the above example, the path 4-> 6-> 7-> 9-> 10-> 11-> 45 is having the maximum number of bends, i.e., 3. The length of this path is 6.
The idea is to traverse the tree for left and right subtrees of the root. While traversing, keep track of the direction of motion (left or right). Whenever, direction of motion changes from left to right or vice versa increment the number of bends in the current path by 1.
On reaching the leaf node, compare the number of bends in the current path with the maximum number of bends(i.e., maxBends) seen so far in a root-to-leaf path. If the number of bends in the current path is greater than the maxBends, then update the maxBends equal to the number of bends in the current path and update the maximum path length (i.e., len) also to the length of the current path.
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.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.