Problem Statement
Given the root of a binary tree, find the length of the longest path where every child node's value is exactly 1 greater than its parent.
The path:
Must move only from parent to child.
Must contain consecutive increasing values.
If no consecutive path of length greater than 1 exists, return -1.
Example 1
1
/ \
2 3
Consecutive path:
1 → 2
Length = 2
Output
2
Example 2
10
/ \
20 30
/ / \
40 60 90
There is no child whose value is exactly parent + 1.
Output
-1
Approach
We use Depth First Search (DFS) to visit every node in the tree.
At each node, we keep track of:
Parent's value
Current consecutive sequence length
For every node:
If the current node's value is parent + 1
Extend the current sequence.
Otherwise
Start a new sequence from this node.
During traversal, we continuously update the maximum sequence length.
Finally:
If the maximum length is only 1, return -1.
Otherwise, return the maximum length.
Algorithm
If the tree is empty, return -1.
Start DFS from the root.
Compare the current node with its parent.
Increase the sequence length if consecutive.
Otherwise, reset the sequence length to 1.
Update the global maximum.
Recursively process the left child.
Recursively process the right child.
Return the answer.
Java Code
class Solution {
int max = 1;
public int longestConsecutive(Node root) {
if (root == null)
return -1;
dfs(root, root.data - 1, 0);
return max == 1 ? -1 : max;
}
private void dfs(Node node, int parent, int len) {
if (node == null)
return;
if (node.data == parent + 1)
len++;
else
len = 1;
max = Math.max(max, len);
dfs(node.left, node.data, len);
dfs(node.right, node.data, len);
}
}
Code Explanation
Global Variable
int max = 1;
Stores the maximum consecutive sequence length found during traversal.
Initially, every node itself forms a sequence of length 1.
longestConsecutive()
public int longestConsecutive(Node root)
This is the main function.
Check for Empty Tree
if (root == null)
return -1;
If there are no nodes, no consecutive path exists.
Start DFS
dfs(root, root.data - 1, 0);
We call DFS with:
Current node =
rootParent value =
root.data - 1Current length =
0
Why root.data - 1?
Suppose the root value is:
10

Join the conversation! Your thoughts help the community grow.