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.
- Maximum Consecutive Increasing Path Length in Binary Tree
- Implementing a BST where every node stores the maximum number of nodes in the path till any leaf
- Maximum Path Sum in a Binary Tree
- Maximum XOR with given value in the path from root to given node in the tree
- Find the maximum path sum between two leaves of a binary tree
- Root to leaf path with maximum distinct nodes
- Find the maximum sum leaf to root path in a Binary Tree
- Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree
- Maximum length cycle that can be formed by joining two nodes of a binary tree
- Root to leaf path sum equal to a given number
- Number of unique paths in tree such that every path has a value greater than K
- Shortest root to leaf path sum equal to a given number
- Root to leaf path product equal to a given number
- Number of Binary Trees for given Preorder Sequence length
- Level with maximum number of nodes
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.