Every node in the Binary Tree can either become part of the path which is starting from one of its parent node or a new path can start from this node itself. The key is to recursively find the path length for the left and right sub tree and then return the maximum. Some cases need to be considered while traversing the tree which are discussed below.
prev : stores the value of the parent node. Initialize prev with one less than value of root node so that the path starting at root can be of length at least 1. len : Stores the path length which ends at the parent of currently visited node.
Case 1: Value of Current Node is prev +1
In this case increase the path length by 1, and then recursively find the path length for the left and the right sub tree then return the maximum between two lengths.
Case 2: Value of Current Node is NOT prev+1
A new path can start from this node, so recursively find the path length for the left and the right sub tree. The path which ends at the parent node of current node might be greater than the path which starts from this node.So take the maximum of the path which starts from this node and which ends at previous node.
// Take the maximum previous path and path under subtree rooted
// with this node.
// A wrapper over maxPathLenUtil().
// Return 0 if root is NULL
if(root == null)
// Else compute Maximum Consecutive Increasing Path
// Length using maxPathLenUtil.
returnmaxPathLenUtil(root, root.val - 1, 0);
// Driver code
Node root = newNode(10);
root.left = newNode(11);
root.right = newNode(9);
root.left.left = newNode(13);
root.left.right = newNode(12);
root.right.left = newNode(13);
root.right.right = newNode(8);
" Increasing Path Length is "+
// This code has been contributed by 29AjayKumar
Maximum Consecutive Increasing Path Length is 3
This article is contributed by Chirag Agarwal. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.