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. Below is the implementation of above idea.
// Find length of the maximum path under subtree rooted with this
// node (The path may or may not include this node)
let newPathLen = Math.max(maxPathLenUtil(root.left, cur_val, 1),
maxPathLenUtil(root.right, cur_val, 1));
// 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 program to test above function
let 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);
document.write("Maximum Consecutive Increasing Path Length is "+
// This code is contributed by rag2127
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 write.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.
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.