Given a Binary Tree, find the length of the longest path consisting of connected nodes such that each next node has a value exactly 1 greater than its parent.
The path must move from parent to child only and follow increasing consecutive values.
If no such path exists, return -1.
Examples:
Input :
Output : 3 Explanation : In the given tree, the longest consecutive parent-to-child path is 1 → 2 → 3 because each next node is exactly 1 greater than its parent, so the answer is 3.
Input :
Output : 3 Explanation : In this tree, the longest consecutive parent-to-child path is 9 → 10 → 11 because each next node is exactly 1 greater than its parent, so the answer is 3.
[Naive Approach] Try for Every Node - O(n²) Time and O(n) Space
For each node, treat it as starting point and find the longest path where each child's value equals parent's value + 1. Track maximum over all nodes. Path must follow increasing consecutive integers.
Create findLength(root) that returns longest consecutive path starting from root.
If root is null, return 0.
Check left child: if left->data == root->data + 1, get leftLength recursively. Do the same for left child.
Return 1 + max(leftLength, rightLength).
In longestConsecutive, compute currentAnswer = findLength(root).
Recursively get leftAnswer and rightAnswer and return max(currentAnswer, max(leftAnswer, rightAnswer)).
If max is 1, return -1 (no valid path of length ≥ 2).
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=nullptr;right=nullptr;}};// Finds the longest consecutive path starting from current nodeintfindLength(Node*root){if(root==nullptr){return0;}intleftLength=0;intrightLength=0;// Continue sequence through left childif(root->left&&root->left->data==root->data+1){leftLength=findLength(root->left);}// Continue sequence through right childif(root->right&&root->right->data==root->data+1){rightLength=findLength(root->right);}return1+max(leftLength,rightLength);}intlongestConsecutive(Node*root){if(root==nullptr){return-1;}// Find longest path starting from current nodeintcurrentAnswer=findLength(root);// Try every node as the starting nodeintleftAnswer=longestConsecutive(root->left);intrightAnswer=longestConsecutive(root->right);intanswer=max(currentAnswer,max(leftAnswer,rightAnswer));return(answer==1?-1:answer);}intmain(){Node*root=newNode(1);root->left=newNode(2);root->right=newNode(4);root->left->left=newNode(3);cout<<longestConsecutive(root);return0;}
Java
// Java program to find longest consecutive sequence in binary treeimportjava.util.*;classNode{intdata;Nodeleft;Noderight;Node(intval){data=val;left=null;right=null;}}classGfG{// Finds the longest consecutive path starting from current nodestaticintfindLength(Noderoot){if(root==null){return0;}intleftLength=0;intrightLength=0;// Continue sequence through left childif(root.left!=null&&root.left.data==root.data+1){leftLength=findLength(root.left);}// Continue sequence through right childif(root.right!=null&&root.right.data==root.data+1){rightLength=findLength(root.right);}return1+Math.max(leftLength,rightLength);}staticintlongestConsecutive(Noderoot){if(root==null){return-1;}// Find longest path starting from current nodeintcurrentAnswer=findLength(root);// Try every node as the starting nodeintleftAnswer=longestConsecutive(root.left);intrightAnswer=longestConsecutive(root.right);intanswer=Math.max(currentAnswer,Math.max(leftAnswer,rightAnswer));return(answer==1?-1:answer);}publicstaticvoidmain(String[]args){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(4);root.left.left=newNode(3);System.out.println(longestConsecutive(root));}}
Python
# Python program to find longest consecutive sequence in binary treeclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Finds the longest consecutive path starting from current nodedeffindLength(root):ifrootisNone:return0leftLength=0rightLength=0# Continue sequence through left childifroot.leftandroot.left.data==root.data+1:leftLength=findLength(root.left)# Continue sequence through right childifroot.rightandroot.right.data==root.data+1:rightLength=findLength(root.right)return1+max(leftLength,rightLength)deflongestConsecutive(root):ifrootisNone:return-1# Find longest path starting from current nodecurrentAnswer=findLength(root)# Try every node as the starting nodeleftAnswer=longestConsecutive(root.left)rightAnswer=longestConsecutive(root.right)answer=max(currentAnswer,max(leftAnswer,rightAnswer))return-1ifanswer==1elseanswer# Driver codeif__name__=="__main__":root=Node(1)root.left=Node(2)root.right=Node(4)root.left.left=Node(3)print(longestConsecutive(root))
C#
// C# program to find longest consecutive sequence in binary treeusingSystem;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}classGfG{// Finds the longest consecutive path starting from current nodestaticintfindLength(Noderoot){if(root==null){return0;}intleftLength=0;intrightLength=0;// Continue sequence through left childif(root.left!=null&&root.left.data==root.data+1){leftLength=findLength(root.left);}// Continue sequence through right childif(root.right!=null&&root.right.data==root.data+1){rightLength=findLength(root.right);}return1+Math.Max(leftLength,rightLength);}staticintlongestConsecutive(Noderoot){if(root==null){return-1;}// Find longest path starting from current nodeintcurrentAnswer=findLength(root);// Try every node as the starting nodeintleftAnswer=longestConsecutive(root.left);intrightAnswer=longestConsecutive(root.right);intanswer=Math.Max(currentAnswer,Math.Max(leftAnswer,rightAnswer));return(answer==1?-1:answer);}staticvoidMain(string[]args){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(4);root.left.left=newNode(3);Console.WriteLine(longestConsecutive(root));}}
JavaScript
// JavaScript program to find longest consecutive sequence in binary treeclassNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Finds the longest consecutive path starting from current nodefunctionfindLength(root){if(root===null){return0;}letleftLength=0;letrightLength=0;// Continue sequence through left childif(root.left&&root.left.data===root.data+1){leftLength=findLength(root.left);}// Continue sequence through right childif(root.right&&root.right.data===root.data+1){rightLength=findLength(root.right);}return1+Math.max(leftLength,rightLength);}functionlongestConsecutive(root){if(root===null){return-1;}// Find longest path starting from current nodeletcurrentAnswer=findLength(root);// Try every node as the starting nodeletleftAnswer=longestConsecutive(root.left);letrightAnswer=longestConsecutive(root.right);letanswer=Math.max(currentAnswer,Math.max(leftAnswer,rightAnswer));returnanswer===1?-1:answer;}// Driver codeconstroot=newNode(1);root.left=newNode(2);root.right=newNode(4);root.left.left=newNode(3);console.log(longestConsecutive(root));
Output
3
[Expected Approach] Single DFS with Parent Tracking - O(n) Time and O(n) Space
Perform DFS while tracking the length of current consecutive path. When moving from parent to child, if child's value equals parent's value + 1, increment current length; otherwise reset to 1. Update global maximum.
3) At the end, return longestPath (if 1, return -1).
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=nullptr;right=nullptr;}};// DFS traversal while maintaining current consecutive lengthvoiddfs(Node*currentNode,Node*parentNode,intcurrentLength,int&longestPath){if(currentNode==nullptr){return;}// Check whether consecutive sequence continuesif(parentNode&¤tNode->data==parentNode->data+1){currentLength++;}else{currentLength=1;}// Update the best answer found so farlongestPath=max(longestPath,currentLength);dfs(currentNode->left,currentNode,currentLength,longestPath);dfs(currentNode->right,currentNode,currentLength,longestPath);}intlongestConsecutive(Node*root){if(root==nullptr){return-1;}intlongestPath=0;dfs(root,nullptr,0,longestPath);return(longestPath==1?-1:longestPath);}intmain(){Node*root=newNode(1);root->left=newNode(2);root->right=newNode(4);root->left->left=newNode(3);cout<<longestConsecutive(root);return0;}
Java
// Java program to find longest consecutive sequence in binary tree using DFSimportjava.util.*;classNode{intdata;Nodeleft;Noderight;Node(intval){data=val;left=null;right=null;}}classGfG{// DFS traversal while maintaining current consecutive lengthstaticvoiddfs(NodecurrentNode,NodeparentNode,intcurrentLength,int[]longestPath){if(currentNode==null){return;}// Check whether consecutive sequence continuesif(parentNode!=null&¤tNode.data==parentNode.data+1){currentLength++;}else{currentLength=1;}// Update the best answer found so farlongestPath[0]=Math.max(longestPath[0],currentLength);dfs(currentNode.left,currentNode,currentLength,longestPath);dfs(currentNode.right,currentNode,currentLength,longestPath);}staticintlongestConsecutive(Noderoot){if(root==null){return-1;}int[]longestPath={0};dfs(root,null,0,longestPath);return(longestPath[0]==1?-1:longestPath[0]);}publicstaticvoidmain(String[]args){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(4);root.left.left=newNode(3);System.out.println(longestConsecutive(root));}}
Python
# Python program to find longest consecutive sequence in binary tree using DFSclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# DFS traversal while maintaining current consecutive lengthdefdfs(currentNode,parentNode,currentLength,longestPath):ifcurrentNodeisNone:return# Check whether consecutive sequence continuesifparentNodeandcurrentNode.data==parentNode.data+1:currentLength+=1else:currentLength=1# Update the best answer found so farlongestPath[0]=max(longestPath[0],currentLength)dfs(currentNode.left,currentNode,currentLength,longestPath)dfs(currentNode.right,currentNode,currentLength,longestPath)deflongestConsecutive(root):ifrootisNone:return-1longestPath=[0]dfs(root,None,0,longestPath)return-1iflongestPath[0]==1elselongestPath[0]# Driver codeif__name__=="__main__":root=Node(1)root.left=Node(2)root.right=Node(4)root.left.left=Node(3)print(longestConsecutive(root))
C#
// C# program to find longest consecutive sequence in binary tree using DFSusingSystem;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}classGfG{// DFS traversal while maintaining current consecutive lengthstaticvoiddfs(NodecurrentNode,NodeparentNode,intcurrentLength,refintlongestPath){if(currentNode==null){return;}// Check whether consecutive sequence continuesif(parentNode!=null&¤tNode.data==parentNode.data+1){currentLength++;}else{currentLength=1;}// Update the best answer found so farlongestPath=Math.Max(longestPath,currentLength);dfs(currentNode.left,currentNode,currentLength,reflongestPath);dfs(currentNode.right,currentNode,currentLength,reflongestPath);}staticintlongestConsecutive(Noderoot){if(root==null){return-1;}intlongestPath=0;dfs(root,null,0,reflongestPath);return(longestPath==1?-1:longestPath);}staticvoidMain(string[]args){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(4);root.left.left=newNode(3);Console.WriteLine(longestConsecutive(root));}}
JavaScript
// JavaScript program to find longest consecutive sequence in binary tree using DFSclassNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// DFS traversal while maintaining current consecutive lengthfunctiondfs(currentNode,parentNode,currentLength,longestPath){if(currentNode===null){return;}// Check whether consecutive sequence continuesif(parentNode&¤tNode.data===parentNode.data+1){currentLength++;}else{currentLength=1;}// Update the best answer found so farlongestPath[0]=Math.max(longestPath[0],currentLength);dfs(currentNode.left,currentNode,currentLength,longestPath);dfs(currentNode.right,currentNode,currentLength,longestPath);}functionlongestConsecutive(root){if(root===null){return-1;}letlongestPath=[0];dfs(root,null,0,longestPath);returnlongestPath[0]===1?-1:longestPath[0];}// Driver codeconstroot=newNode(1);root.left=newNode(2);root.right=newNode(4);root.left.left=newNode(3);console.log(longestConsecutive(root));