Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Length of the Longest Consecutive 1s in Binary Representation
Next article icon

Longest consecutive sequence in Binary tree

Last Updated : 10 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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 :

Recommended Practice
Longest consecutive sequence in Binary tree
Try It!

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>
 
 
Output
3

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

 



Next Article
Length of the Longest Consecutive 1s in Binary Representation

U

Utkarsh Trivedi
Improve
Article Tags :
  • DSA
  • Tree
  • Binary Tree
Practice Tags :
  • Tree

Similar Reads

  • Longest Consecutive Subsequence
    Given an array of integers, the task is to find the length of the longest subsequence such that elements in the subsequence are consecutive integers, the consecutive numbers can be in any order. Examples: Input: arr[] = [2, 6, 1, 9, 4, 5, 3]Output: 6Explanation: The consecutive numbers here are from
    10 min read
  • Longest Increasing consecutive subsequence
    Given N elements, write a program that prints the length of the longest increasing consecutive subsequence. Examples: Input : a[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} Output : 6 Explanation: 3, 4, 5, 6, 7, 8 is the longest increasing subsequence whose adjacent element differs by one. Input : a[] = {6
    10 min read
  • Longest Increasing consecutive subsequence | Set-2
    Given an array arr[] of N elements, the task is to find the length of the longest increasing subsequence whose adjacent element difference is one. Examples: Input: arr[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} Output: 6 Explanation: The subsequence {3, 4, 5, 6, 7, 8} is the longest increasing subsequenc
    5 min read
  • Longest subsequence with consecutive English alphabets
    Given string S, the task is to find the length of the longest subsequence of the consecutive lowercase alphabets. Examples: Input: S = "acbdcfhg"Output: 3Explanation: String "abc" is the longest subsequence of consecutive lowercase alphabets.Therefore, print 3 as it is the length of the subsequence
    6 min read
  • Length of the Longest Consecutive 1s in Binary Representation
    Given a number N, The task is to find the length of the longest consecutive 1s series in its binary representation.Examples : Input: N = 14Output: 3Explanation: The binary representation of 14 is 1110. Input: N = 222Output: 4Explanation: The binary representation of 222 is 11011110. Recommended Prac
    9 min read
  • Length of second longest sequence of consecutive 1s in a binary array
    Given a binary array arr[] of size N, the task is to find the length of the second longest sequence of consecutive 1s present in the array. Examples: Input: arr[] = {1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0} Output: 4 3 Explanation: Longest sequence of consecutive ones is 4 i.e {arr[7], ... arr[10]}
    7 min read
  • Find the largest Complete Subtree in a given Binary Tree
    Given a Binary Tree, the task is to find the size and also the inorder traversal of the largest Complete sub-tree in the given Binary Tree. Complete Binary Tree - A Binary tree is a Complete Binary Tree if all levels are filled except possibly the last level and the last level has all keys as left a
    13 min read
  • Maximum Consecutive Increasing Path Length in Binary Tree
    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: 10 / \ / \ 11 9 / \ /\ / \ / \ 13 12 13 8 Maximum Consecutive Path Length is 3 (10, 11, 12) Note: 10, 9 ,8 is NOT co
    10 min read
  • Printing longest Increasing consecutive subsequence
    Given n elements, write a program that prints the longest increasing subsequence whose adjacent element difference is one. Examples: Input : a[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} Output : 3 4 5 6 7 8 Explanation: 3, 4, 5, 6, 7, 8 is the longest increasing subsequence whose adjacent element differs
    8 min read
  • Largest BST in a Binary Tree
    Given a Binary Tree, the task is to return the size of the largest subtree which is also a Binary Search Tree (BST). If the complete Binary Tree is BST, then return the size of the whole tree. Examples: Input: Output: 3 Explanation: The below subtree is the maximum size BST: Input: Output: 3 Explana
    14 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences