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.
- Write a Program to Find the Maximum Depth or Height of a Tree
- Root to leaf path sum equal to a given number
- Maximum width of a binary tree
- Find the maximum sum leaf to root path in a Binary Tree
- Remove all nodes which don't lie in any path with sum>= k
- Find the maximum path sum between two leaves of a binary tree
- Remove nodes on root to leaf paths of length < K
- Maximum Path Sum in a Binary Tree
- Maximum difference between node and its ancestor in Binary Tree
- Number of ways to traverse an N-ary tree
- Find a number in minimum steps
- Maximum Consecutive Increasing Path Length in Binary Tree
- Check if there is a root to leaf path with given sequence
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Find maximum level sum in Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.