Longest consecutive sequence in Binary tree

Last Updated : 8 Jun, 2026

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 :

2056958123

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 :

2056958124

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.

Try It Yourself
redirect icon

[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>
using namespace std;

class Node
{
  public:
    int data;
    Node *left;
    Node *right;

    Node(int val)
    {
        data = val;
        left = nullptr;
        right = nullptr;
    }
};

// Finds the longest consecutive path starting from current node
int findLength(Node *root)
{
    if (root == nullptr)
    {
        return 0;
    }

    int leftLength = 0;
    int rightLength = 0;

    // Continue sequence through left child
    if (root->left && root->left->data == root->data + 1)
    {
        leftLength = findLength(root->left);
    }

    // Continue sequence through right child
    if (root->right && root->right->data == root->data + 1)
    {
        rightLength = findLength(root->right);
    }

    return 1 + max(leftLength, rightLength);
}

int longestConsecutive(Node *root)
{
    if (root == nullptr)
    {
        return -1;
    }

    // Find longest path starting from current node
    int currentAnswer = findLength(root);

    // Try every node as the starting node
    int leftAnswer = longestConsecutive(root->left);
    int rightAnswer = longestConsecutive(root->right);

    int answer = max(currentAnswer, max(leftAnswer, rightAnswer));

    return (answer == 1 ? -1 : answer);
}

int main()
{
    Node *root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(4);
    root->left->left = new Node(3);

    cout << longestConsecutive(root);

    return 0;
}
Java
// Java program to find longest consecutive sequence in binary tree
import java.util.*;

class Node {
    int data;
    Node left;
    Node right;
    
    Node(int val) {
        data = val;
        left = null;
        right = null;
    }
}

class GfG {
    
    // Finds the longest consecutive path starting from current node
    static int findLength(Node root) {
        if (root == null) {
            return 0;
        }
        
        int leftLength = 0;
        int rightLength = 0;
        
        // Continue sequence through left child
        if (root.left != null && root.left.data == root.data + 1) {
            leftLength = findLength(root.left);
        }
        
        // Continue sequence through right child
        if (root.right != null && root.right.data == root.data + 1) {
            rightLength = findLength(root.right);
        }
        
        return 1 + Math.max(leftLength, rightLength);
    }
    
    static int longestConsecutive(Node root) {
        if (root == null) {
            return -1;
        }
        
        // Find longest path starting from current node
        int currentAnswer = findLength(root);
        
        // Try every node as the starting node
        int leftAnswer = longestConsecutive(root.left);
        int rightAnswer = longestConsecutive(root.right);
        
        int answer = Math.max(currentAnswer, Math.max(leftAnswer, rightAnswer));
        
        return (answer == 1 ? -1 : answer);
    }
    
    public static void main(String[] args) {
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(4);
        root.left.left = new Node(3);
        
        System.out.println(longestConsecutive(root));
    }
}
Python
# Python program to find longest consecutive sequence in binary tree

class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

# Finds the longest consecutive path starting from current node
def findLength(root):
    if root is None:
        return 0
    
    leftLength = 0
    rightLength = 0
    
    # Continue sequence through left child
    if root.left and root.left.data == root.data + 1:
        leftLength = findLength(root.left)
    
    # Continue sequence through right child
    if root.right and root.right.data == root.data + 1:
        rightLength = findLength(root.right)
    
    return 1 + max(leftLength, rightLength)

def longestConsecutive(root):
    if root is None:
        return -1
    
    # Find longest path starting from current node
    currentAnswer = findLength(root)
    
    # Try every node as the starting node
    leftAnswer = longestConsecutive(root.left)
    rightAnswer = longestConsecutive(root.right)
    
    answer = max(currentAnswer, max(leftAnswer, rightAnswer))
    
    return -1 if answer == 1 else answer

# Driver code
if __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 System;

class Node {
    public int data;
    public Node left;
    public Node right;
    
    public Node(int val) {
        data = val;
        left = null;
        right = null;
    }
}

class GfG {
    
    // Finds the longest consecutive path starting from current node
    static int findLength(Node root) {
        if (root == null) {
            return 0;
        }
        
        int leftLength = 0;
        int rightLength = 0;
        
        // Continue sequence through left child
        if (root.left != null && root.left.data == root.data + 1) {
            leftLength = findLength(root.left);
        }
        
        // Continue sequence through right child
        if (root.right != null && root.right.data == root.data + 1) {
            rightLength = findLength(root.right);
        }
        
        return 1 + Math.Max(leftLength, rightLength);
    }
    
    static int longestConsecutive(Node root) {
        if (root == null) {
            return -1;
        }
        
        // Find longest path starting from current node
        int currentAnswer = findLength(root);
        
        // Try every node as the starting node
        int leftAnswer = longestConsecutive(root.left);
        int rightAnswer = longestConsecutive(root.right);
        
        int answer = Math.Max(currentAnswer, Math.Max(leftAnswer, rightAnswer));
        
        return (answer == 1 ? -1 : answer);
    }
    
    static void Main(string[] args) {
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(4);
        root.left.left = new Node(3);
        
        Console.WriteLine(longestConsecutive(root));
    }
}
JavaScript
// JavaScript program to find longest consecutive sequence in binary tree

class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

// Finds the longest consecutive path starting from current node
function findLength(root) {
    if (root === null) {
        return 0;
    }
    
    let leftLength = 0;
    let rightLength = 0;
    
    // Continue sequence through left child
    if (root.left && root.left.data === root.data + 1) {
        leftLength = findLength(root.left);
    }
    
    // Continue sequence through right child
    if (root.right && root.right.data === root.data + 1) {
        rightLength = findLength(root.right);
    }
    
    return 1 + Math.max(leftLength, rightLength);
}

function longestConsecutive(root) {
    if (root === null) {
        return -1;
    }
    
    // Find longest path starting from current node
    let currentAnswer = findLength(root);
    
    // Try every node as the starting node
    let leftAnswer = longestConsecutive(root.left);
    let rightAnswer = longestConsecutive(root.right);
    
    let answer = Math.max(currentAnswer, Math.max(leftAnswer, rightAnswer));
    
    return answer === 1 ? -1 : answer;
}

// Driver code
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(4);
root.left.left = new Node(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.

1) Initialize longestPath = 0 and call dfs(root, nullptr, 0, longestPath).

2) Do the following in dfs(currentNode, parentNode, currentLength, longestPath):

  • If currentNode is null, return.
  • If parent exists and currentNode->data == parentNode->data + 1, increment currentLength.
  • Else reset currentLength = 1.
  • Update longestPath = max(longestPath, currentLength).
  • Recursively call dfs on left and right children.

3) At the end, return longestPath (if 1, return -1).

C++
#include <bits/stdc++.h>
using namespace std;

class Node
{
  public:
    int data;
    Node *left;
    Node *right;

    Node(int val)
    {
        data = val;
        left = nullptr;
        right = nullptr;
    }
};

// DFS traversal while maintaining current consecutive length
void dfs(Node *currentNode, Node *parentNode, int currentLength, int &longestPath)
{
    if (currentNode == nullptr)
    {
        return;
    }

    // Check whether consecutive sequence continues
    if (parentNode && currentNode->data == parentNode->data + 1)
    {
        currentLength++;
    }
    else
    {
        currentLength = 1;
    }

    // Update the best answer found so far
    longestPath = max(longestPath, currentLength);

    dfs(currentNode->left, currentNode, currentLength, longestPath);

    dfs(currentNode->right, currentNode, currentLength, longestPath);
}

int longestConsecutive(Node *root)
{
    if (root == nullptr)
    {
        return -1;
    }

    int longestPath = 0;

    dfs(root, nullptr, 0, longestPath);

    return (longestPath == 1 ? -1 : longestPath);
}

int main()
{
    Node *root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(4);
    root->left->left = new Node(3);

    cout << longestConsecutive(root);

    return 0;
}
Java
// Java program to find longest consecutive sequence in binary tree using DFS
import java.util.*;

class Node {
    int data;
    Node left;
    Node right;
    
    Node(int val) {
        data = val;
        left = null;
        right = null;
    }
}

class GfG {
    
    // DFS traversal while maintaining current consecutive length
    static void dfs(Node currentNode, Node parentNode, 
                    int currentLength, int[] longestPath) {
        if (currentNode == null) {
            return;
        }
        
        // Check whether consecutive sequence continues
        if (parentNode != null && 
            currentNode.data == parentNode.data + 1) {
            currentLength++;
        } else {
            currentLength = 1;
        }
        
        // Update the best answer found so far
        longestPath[0] = Math.max(longestPath[0], currentLength);
        
        dfs(currentNode.left, currentNode, currentLength, longestPath);
        dfs(currentNode.right, currentNode, currentLength, longestPath);
    }
    
    static int longestConsecutive(Node root) {
        if (root == null) {
            return -1;
        }
        
        int[] longestPath = {0};
        
        dfs(root, null, 0, longestPath);
        
        return (longestPath[0] == 1 ? -1 : longestPath[0]);
    }
    
    public static void main(String[] args) {
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(4);
        root.left.left = new Node(3);
        
        System.out.println(longestConsecutive(root));
    }
}
Python
# Python program to find longest consecutive sequence in binary tree using DFS

class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

# DFS traversal while maintaining current consecutive length
def dfs(currentNode, parentNode, currentLength, longestPath):
    if currentNode is None:
        return
    
    # Check whether consecutive sequence continues
    if parentNode and currentNode.data == parentNode.data + 1:
        currentLength += 1
    else:
        currentLength = 1
    
    # Update the best answer found so far
    longestPath[0] = max(longestPath[0], currentLength)
    
    dfs(currentNode.left, currentNode, currentLength, longestPath)
    dfs(currentNode.right, currentNode, currentLength, longestPath)

def longestConsecutive(root):
    if root is None:
        return -1
    
    longestPath = [0]
    
    dfs(root, None, 0, longestPath)
    
    return -1 if longestPath[0] == 1 else longestPath[0]

# Driver code
if __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 DFS
using System;

class Node {
    public int data;
    public Node left;
    public Node right;
    
    public Node(int val) {
        data = val;
        left = null;
        right = null;
    }
}

class GfG {
    
    // DFS traversal while maintaining current consecutive length
    static void dfs(Node currentNode, Node parentNode, 
                    int currentLength, ref int longestPath) {
        if (currentNode == null) {
            return;
        }
        
        // Check whether consecutive sequence continues
        if (parentNode != null && 
            currentNode.data == parentNode.data + 1) {
            currentLength++;
        } else {
            currentLength = 1;
        }
        
        // Update the best answer found so far
        longestPath = Math.Max(longestPath, currentLength);
        
        dfs(currentNode.left, currentNode, currentLength, ref longestPath);
        dfs(currentNode.right, currentNode, currentLength, ref longestPath);
    }
    
    static int longestConsecutive(Node root) {
        if (root == null) {
            return -1;
        }
        
        int longestPath = 0;
        
        dfs(root, null, 0, ref longestPath);
        
        return (longestPath == 1 ? -1 : longestPath);
    }
    
    static void Main(string[] args) {
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(4);
        root.left.left = new Node(3);
        
        Console.WriteLine(longestConsecutive(root));
    }
}
JavaScript
// JavaScript program to find longest consecutive sequence in binary tree using DFS

class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

// DFS traversal while maintaining current consecutive length
function dfs(currentNode, parentNode, currentLength, longestPath) {
    if (currentNode === null) {
        return;
    }
    
    // Check whether consecutive sequence continues
    if (parentNode && currentNode.data === parentNode.data + 1) {
        currentLength++;
    } else {
        currentLength = 1;
    }
    
    // Update the best answer found so far
    longestPath[0] = Math.max(longestPath[0], currentLength);
    
    dfs(currentNode.left, currentNode, currentLength, longestPath);
    dfs(currentNode.right, currentNode, currentLength, longestPath);
}

function longestConsecutive(root) {
    if (root === null) {
        return -1;
    }
    
    let longestPath = [0];
    
    dfs(root, null, 0, longestPath);
    
    return longestPath[0] === 1 ? -1 : longestPath[0];
}

// Driver code
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(4);
root.left.left = new Node(3);

console.log(longestConsecutive(root));

Output
3

 

Comment