Longest consecutive sequence in Binary tree
Last Updated :
10 Mar, 2023
Given a Binary Tree find the length of the longest path which comprises of nodes with consecutive values in increasing order. Every node is considered as a path of length 1.
Examples:
In below diagram binary tree with longest consecutive path(LCP) are shown :

We can solve above problem recursively. At each node we need information of its parent node, if current node has value one more than its parent node then it makes a consecutive path, at each node we will compare node’s value with its parent value and update the longest consecutive path accordingly.
For getting the value of parent node, we will pass the (node_value + 1) as an argument to the recursive method and compare the node value with this argument value, if satisfies, update the current length of consecutive path otherwise reinitialize current path length by 1.
Please see below code for better understanding :
C++
// C/C++ program to find longest consecutive
// sequence in binary tree
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data, pointer to left
child and a pointer to right child */
struct Node
{
int data;
Node *left, *right;
};
// A utility function to create a node
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Utility method to return length of longest
// consecutive sequence of tree
void longestConsecutiveUtil(Node* root, int curLength,
int expected, int& res)
{
if (root == NULL)
return;
// if root data has one more than its parent
// then increase current length
if (root->data == expected)
curLength++;
else
curLength = 1;
// update the maximum by current length
res = max(res, curLength);
// recursively call left and right subtree with
// expected value 1 more than root data
longestConsecutiveUtil(root->left, curLength,
root->data + 1, res);
longestConsecutiveUtil(root->right, curLength,
root->data + 1, res);
}
// method returns length of longest consecutive
// sequence rooted at node root
int longestConsecutive(Node* root)
{
if (root == NULL)
return 0;
int res = 0;
// call utility method with current length 0
longestConsecutiveUtil(root, 0, root->data, res);
return res;
}
// Driver code to test above methods
int main()
{
Node* root = newNode(6);
root->right = newNode(9);
root->right->left = newNode(7);
root->right->right = newNode(10);
root->right->right->right = newNode(11);
printf("%d\n", longestConsecutive(root));
return 0;
}
Java
// Java program to find longest consecutive
// sequence in binary tree
class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}
class Result
{
int res = 0;
}
class BinaryTree
{
Node root;
// method returns length of longest consecutive
// sequence rooted at node root
int longestConsecutive(Node root)
{
if (root == null)
return 0;
Result res = new Result();
// call utility method with current length 0
longestConsecutiveUtil(root, 0, root.data, res);
return res.res;
}
// Utility method to return length of longest
// consecutive sequence of tree
private void longestConsecutiveUtil(Node root, int curlength,
int expected, Result res)
{
if (root == null)
return;
// if root data has one more than its parent
// then increase current length
if (root.data == expected)
curlength++;
else
curlength = 1;
// update the maximum by current length
res.res = Math.max(res.res, curlength);
// recursively call left and right subtree with
// expected value 1 more than root data
longestConsecutiveUtil(root.left, curlength, root.data + 1, res);
longestConsecutiveUtil(root.right, curlength, root.data + 1, res);
}
// Driver code
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(6);
tree.root.right = new Node(9);
tree.root.right.left = new Node(7);
tree.root.right.right = new Node(10);
tree.root.right.right.right = new Node(11);
System.out.println(tree.longestConsecutive(tree.root));
}
}
// This code is contributed by shubham96301
Python3
# Python3 program to find longest consecutive
# sequence in binary tree
# A utility class to create a node
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# Utility method to return length of
# longest consecutive sequence of tree
def longestConsecutiveUtil(root, curLength,
expected, res):
if (root == None):
return
# if root data has one more than its
# parent then increase current length
if (root.data == expected):
curLength += 1
else:
curLength = 1
# update the maximum by current length
res[0] = max(res[0], curLength)
# recursively call left and right subtree
# with expected value 1 more than root data
longestConsecutiveUtil(root.left, curLength,
root.data + 1, res)
longestConsecutiveUtil(root.right, curLength,
root.data + 1, res)
# method returns length of longest consecutive
# sequence rooted at node root
def longestConsecutive(root):
if (root == None):
return 0
res = [0]
# call utility method with current length 0
longestConsecutiveUtil(root, 0, root.data, res)
return res[0]
# Driver Code
if __name__ == '__main__':
root = newNode(6)
root.right = newNode(9)
root.right.left = newNode(7)
root.right.right = newNode(10)
root.right.right.right = newNode(11)
print(longestConsecutive(root))
# This code is contributed by PranchalK
C#
// C# program to find longest consecutive
// sequence in binary tree
using System;
class Node
{
public int data;
public Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
class Result
{
public int res = 0;
}
class GFG
{
Node root;
// method returns length of longest consecutive
// sequence rooted at node root
int longestConsecutive(Node root)
{
if (root == null)
return 0;
Result res = new Result();
// call utility method with current length 0
longestConsecutiveUtil(root, 0, root.data, res);
return res.res;
}
// Utility method to return length of longest
// consecutive sequence of tree
private void longestConsecutiveUtil(Node root, int curlength,
int expected, Result res)
{
if (root == null)
return;
// if root data has one more than its parent
// then increase current length
if (root.data == expected)
curlength++;
else
curlength = 1;
// update the maximum by current length
res.res = Math.Max(res.res, curlength);
// recursively call left and right subtree with
// expected value 1 more than root data
longestConsecutiveUtil(root.left, curlength,
root.data + 1, res);
longestConsecutiveUtil(root.right, curlength,
root.data + 1, res);
}
// Driver code
public static void Main(String []args)
{
GFG tree = new GFG();
tree.root = new Node(6);
tree.root.right = new Node(9);
tree.root.right.left = new Node(7);
tree.root.right.right = new Node(10);
tree.root.right.right.right = new Node(11);
Console.WriteLine(tree.longestConsecutive(tree.root));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// JavaScript program to find longest consecutive
// sequence in binary tree
class Node
{
constructor(item)
{
this.data=item;
this.left = this.right = null;
}
}
let res = 0;
let root;
function longestConsecutive(root)
{
if (root == null)
return 0;
res=[0];
// call utility method with current length 0
longestConsecutiveUtil(root, 0, root.data, res);
return res[0];
}
// Utility method to return length of longest
// consecutive sequence of tree
function longestConsecutiveUtil(root,curlength, expected,res)
{
if (root == null)
return;
// if root data has one more than its parent
// then increase current length
if (root.data == expected)
curlength++;
else
curlength = 1;
// update the maximum by current length
res[0] = Math.max(res[0], curlength);
// recursively call left and right subtree with
// expected value 1 more than root data
longestConsecutiveUtil(root.left, curlength,
root.data + 1, res);
longestConsecutiveUtil(root.right, curlength,
root.data + 1, res);
}
// Driver code
root = new Node(6);
root.right = new Node(9);
root.right.left = new Node(7);
root.right.right = new Node(10);
root.right.right.right = new Node(11);
document.write(longestConsecutive(root));
// This code is contributed by rag2127
</script>
Time Complexity: O(N) where N is the Number of nodes in a given binary tree.
Auxiliary Space: O(log(N))
Also discussed on below link:
Maximum Consecutive Increasing Path Length in Binary Tree
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read