Maximum Consecutive Increasing Path Length 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:
10
/ \
/ \
11 9
/ \ /\
/ \ / \
13 12 13 8
Maximum Consecutive Path Length is 3 (10, 11, 12)
Note: 10, 9 ,8 is NOT considered since
the nodes should be in increasing order.
5
/ \
/ \
8 11
/ \
/ \
9 10
/ /
/ /
6 15
Maximum Consecutive Path Length is 2 (8, 9).
Every node in the Binary Tree can either become part of the path which is starting from one of its parent node or a new path can start from this node itself. The key is to recursively find the path length for the left and right sub tree and then return the maximum. Some cases need to be considered while traversing the tree which are discussed below.
- prev : stores the value of the parent node. Initialize prev with one less than value of root node so that the path starting at root can be of length at least 1.
- len : Stores the path length which ends at the parent of currently visited node.
Case 1: Value of Current Node is prev +1
In this case increase the path length by 1, and then recursively find the path length for the left and the right sub tree then return the maximum between two lengths.
Case 2: Value of Current Node is NOT prev+1
A new path can start from this node, so recursively find the path length for the left and the right sub tree. The path which ends at the parent node of current node might be greater than the path which starts from this node.So take the maximum of the path which starts from this node and which ends at previous node.
Below is the implementation of above idea.
C++
// C++ Program to find Maximum Consecutive
// Path Length in a Binary Tree
#include <bits/stdc++.h>
using namespace std;
// To represent a node of a Binary Tree
struct Node
{
Node *left, *right;
int val;
};
// Create a new Node and return its address
Node *newNode(int val)
{
Node *temp = new Node();
temp->val = val;
temp->left = temp->right = NULL;
return temp;
}
// Returns the maximum consecutive Path Length
int maxPathLenUtil(Node *root, int prev_val, int prev_len)
{
if (!root)
return prev_len;
// Get the value of Current Node
// The value of the current node will be
// prev Node for its left and right children
int cur_val = root->val;
// If current node has to be a part of the
// consecutive path then it should be 1 greater
// than the value of the previous node
if (cur_val == prev_val+1)
{
// a) Find the length of the Left Path
// b) Find the length of the Right Path
// Return the maximum of Left path and Right path
return max(maxPathLenUtil(root->left, cur_val, prev_len+1),
maxPathLenUtil(root->right, cur_val, prev_len+1));
}
// Find length of the maximum path under subtree rooted with this
// node (The path may or may not include this node)
int newPathLen = max(maxPathLenUtil(root->left, cur_val, 1),
maxPathLenUtil(root->right, cur_val, 1));
// Take the maximum previous path and path under subtree rooted
// with this node.
return max(prev_len, newPathLen);
}
// A wrapper over maxPathLenUtil().
int maxConsecutivePathLength(Node *root)
{
// Return 0 if root is NULL
if (root == NULL)
return 0;
// Else compute Maximum Consecutive Increasing Path
// Length using maxPathLenUtil.
return maxPathLenUtil(root, root->val-1, 0);
}
//Driver program to test above function
int main()
{
Node *root = newNode(10);
root->left = newNode(11);
root->right = newNode(9);
root->left->left = newNode(13);
root->left->right = newNode(12);
root->right->left = newNode(13);
root->right->right = newNode(8);
cout << "Maximum Consecutive Increasing Path Length is "
<< maxConsecutivePathLength(root);
return 0;
}
Java
// Java Program to find Maximum Consecutive
// Path Length in a Binary Tree
import java.util.*;
class GfG {
// To represent a node of a Binary Tree
static class Node
{
Node left, right;
int val;
}
// Create a new Node and return its address
static Node newNode(int val)
{
Node temp = new Node();
temp.val = val;
temp.left = null;
temp.right = null;
return temp;
}
// Returns the maximum consecutive Path Length
static int maxPathLenUtil(Node root, int prev_val, int prev_len)
{
if (root == null)
return prev_len;
// Get the value of Current Node
// The value of the current node will be
// prev Node for its left and right children
int cur_val = root.val;
// If current node has to be a part of the
// consecutive path then it should be 1 greater
// than the value of the previous node
if (cur_val == prev_val+1)
{
// a) Find the length of the Left Path
// b) Find the length of the Right Path
// Return the maximum of Left path and Right path
return Math.max(maxPathLenUtil(root.left, cur_val, prev_len+1),
maxPathLenUtil(root.right, cur_val, prev_len+1));
}
// Find length of the maximum path under subtree rooted with this
// node (The path may or may not include this node)
int newPathLen = Math.max(maxPathLenUtil(root.left, cur_val, 1),
maxPathLenUtil(root.right, cur_val, 1));
// Take the maximum previous path and path under subtree rooted
// with this node.
return Math.max(prev_len, newPathLen);
}
// A wrapper over maxPathLenUtil().
static int maxConsecutivePathLength(Node root)
{
// Return 0 if root is NULL
if (root == null)
return 0;
// Else compute Maximum Consecutive Increasing Path
// Length using maxPathLenUtil.
return maxPathLenUtil(root, root.val-1, 0);
}
//Driver program to test above function
public static void main(String[] args)
{
Node root = newNode(10);
root.left = newNode(11);
root.right = newNode(9);
root.left.left = newNode(13);
root.left.right = newNode(12);
root.right.left = newNode(13);
root.right.right = newNode(8);
System.out.println("Maximum Consecutive Increasing Path Length is "+maxConsecutivePathLength(root));
}
}
Python3
# Python program to find Maximum consecutive
# path length in binary tree
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# Returns the maximum consecutive path length
def maxPathLenUtil(root, prev_val, prev_len):
if root is None:
return prev_len
# Get the value of current node
# The value of the current node will be
# prev node for its left and right children
curr_val = root.val
# If current node has to be a part of the
# consecutive path then it should be 1 greater
# than the value of the previous node
if curr_val == prev_val +1 :
# a) Find the length of the left path
# b) Find the length of the right path
# Return the maximum of left path and right path
return max(maxPathLenUtil(root.left, curr_val, prev_len+1),
maxPathLenUtil(root.right, curr_val, prev_len+1))
# Find the length of the maximum path under subtree
# rooted with this node
newPathLen = max(maxPathLenUtil(root.left, curr_val, 1),
maxPathLenUtil(root.right, curr_val, 1))
# Take the maximum previous path and path under subtree
# rooted with this node
return max(prev_len , newPathLen)
# A Wrapper over maxPathLenUtil()
def maxConsecutivePathLength(root):
# Return 0 if root is None
if root is None:
return 0
# Else compute maximum consecutive increasing path
# length using maxPathLenUtil
return maxPathLenUtil(root, root.val -1 , 0)
# Driver program to test above function
root = Node(10)
root.left = Node(11)
root.right = Node(9)
root.left.left = Node(13)
root.left.right = Node(12)
root.right.left = Node(13)
root.right.right = Node(8)
print ("Maximum Consecutive Increasing Path Length is",)
print (maxConsecutivePathLength(root))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
C#
// C# Program to find Maximum Consecutive
// Path Length in a Binary Tree
using System;
class GfG
{
// To represent a node of a Binary Tree
class Node
{
public Node left, right;
public int val;
}
// Create a new Node and return its address
static Node newNode(int val)
{
Node temp = new Node();
temp.val = val;
temp.left = null;
temp.right = null;
return temp;
}
// Returns the maximum consecutive Path Length
static int maxPathLenUtil(Node root,
int prev_val, int prev_len)
{
if (root == null)
return prev_len;
// Get the value of Current Node
// The value of the current node will be
// prev Node for its left and right children
int cur_val = root.val;
// If current node has to be a part of the
// consecutive path then it should be 1 greater
// than the value of the previous node
if (cur_val == prev_val+1)
{
// a) Find the length of the Left Path
// b) Find the length of the Right Path
// Return the maximum of Left path and Right path
return Math.Max(maxPathLenUtil(root.left, cur_val, prev_len+1),
maxPathLenUtil(root.right, cur_val, prev_len+1));
}
// Find length of the maximum path under subtree rooted with this
// node (The path may or may not include this node)
int newPathLen = Math.Max(maxPathLenUtil(root.left, cur_val, 1),
maxPathLenUtil(root.right, cur_val, 1));
// Take the maximum previous path and path under subtree rooted
// with this node.
return Math.Max(prev_len, newPathLen);
}
// A wrapper over maxPathLenUtil().
static int maxConsecutivePathLength(Node root)
{
// Return 0 if root is NULL
if (root == null)
return 0;
// Else compute Maximum Consecutive Increasing Path
// Length using maxPathLenUtil.
return maxPathLenUtil(root, root.val - 1, 0);
}
// Driver code
public static void Main(String[] args)
{
Node root = newNode(10);
root.left = newNode(11);
root.right = newNode(9);
root.left.left = newNode(13);
root.left.right = newNode(12);
root.right.left = newNode(13);
root.right.right = newNode(8);
Console.WriteLine("Maximum Consecutive" +
" Increasing Path Length is "+
maxConsecutivePathLength(root));
}
}
// This code has been contributed by 29AjayKumar
JavaScript
<script>
// Javascript Program to find Maximum Consecutive
// Path Length in a Binary Tree
// To represent a node of a Binary Tree
class Node
{
constructor(val)
{
this.val = val;
this.left = this.right = null;
}
}
// Returns the maximum consecutive Path Length
function maxPathLenUtil(root,prev_val,prev_len)
{
if (root == null)
return prev_len;
// Get the value of Current Node
// The value of the current node will be
// prev Node for its left and right children
let cur_val = root.val;
// If current node has to be a part of the
// consecutive path then it should be 1 greater
// than the value of the previous node
if (cur_val == prev_val+1)
{
// a) Find the length of the Left Path
// b) Find the length of the Right Path
// Return the maximum of Left path and Right path
return Math.max(maxPathLenUtil(root.left, cur_val, prev_len+1),
maxPathLenUtil(root.right, cur_val, prev_len+1));
}
// Find length of the maximum path under subtree rooted with this
// node (The path may or may not include this node)
let newPathLen = Math.max(maxPathLenUtil(root.left, cur_val, 1),
maxPathLenUtil(root.right, cur_val, 1));
// Take the maximum previous path and path under subtree rooted
// with this node.
return Math.max(prev_len, newPathLen);
}
// A wrapper over maxPathLenUtil().
function maxConsecutivePathLength(root)
{
// Return 0 if root is NULL
if (root == null)
return 0;
// Else compute Maximum Consecutive Increasing Path
// Length using maxPathLenUtil.
return maxPathLenUtil(root, root.val-1, 0);
}
// Driver program to test above function
let root = new Node(10);
root.left = new Node(11);
root.right = new Node(9);
root.left.left = new Node(13);
root.left.right = new Node(12);
root.right.left = new Node(13);
root.right.right = new Node(8);
document.write("Maximum Consecutive Increasing Path Length is "+
maxConsecutivePathLength(root)+"<br>");
// This code is contributed by rag2127
</script>
OutputMaximum Consecutive Increasing Path Length is 3
Time Complexity: O(n^2), where n is the number of nodes in the given binary tree.
Auxiliary Space: O(log(n))
Similar Reads
Longest consecutive sequence 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: In below diagram binary tree with longest consecutive path(LCP) are shown : Recommended PracticeLongest consecutive s
7 min read
Get maximum left node in binary tree
Given a tree, the task is to find the maximum in an only left node of the binary tree. Examples: Input : 7 / \ 6 5 / \ / \ 4 3 2 1 Output : 6 Input : 1 / \ 2 3 / / \ 4 5 6 \ / \ 7 8 9 Output : 8 Traverse with inorder traversal and Apply the condition for the left node only and get maximum of left no
10 min read
Find maximum path length in a binary matrix
Given a square matrix mat every element of which is either 0 or 1. A value 1 means connected and 0 means not connected. The task is to find the largest length of a path in the matrix after changing atmost one 0 to 1. A path is a 4-directionally connected group of 1s. Examples: Input: mat[][] = {{1,
9 min read
Find the level with maximum setbit count in given Binary Tree
Given a binary tree having N nodes, the task is to find the level having the maximum number of setbits. Note: If two levels have same number of setbits print the one which has less no of nodes. If nodes are equal print the first level from top to bottom Examples: Input: 2 / \ 5 3 / \6 1Output: 2Expl
11 min read
Maximum cost of splitting given Binary Tree into two halves
Given a Binary Tree with N nodes valued 0 to N - 1 and N-1 edges and an array arr[] consisting of values of edges, the task is to find the maximum cost of splitting the tree into two halves. The cost of splitting a tree is equal to the product of sum of node values of the splitted subtrees. Examples
11 min read
Maximum parent children sum in Binary tree
Given a Binary Tree, find the maximum sum in a binary tree by adding the parent with its children. Exactly three Node needs to be added. If the tree does not have a node with both of its children as not NULL, return 0. We simply traverse the tree and find the Node that has the maximum sum. We need t
5 min read
Find maximum level product in Binary Tree
Given a Binary Tree having positive and negative nodes, the task is to find maximum product level in it. Examples: Input : 4 / \ 2 -5 / \ /\ -1 3 -2 6 Output: 36 Explanation : Product of all nodes of 0'th level is 4 Product of all nodes of 1'th level is -10 Product of all nodes of 2'th level is 36 H
9 min read
Find maximum level sum in Binary Tree
Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum level in it. Examples: Input : 4 / \ 2 -5 / \ /\ -1 3 -2 6Output: 6Explanation :Sum of all nodes of 0'th level is 4Sum of all nodes of 1'th level is -3Sum of all nodes of 0'th level is 6Hence maximum sum is 6
15+ min read
Count of strictly increasing and decreasing paths in directed Binary Tree
Given a directed binary tree of N nodes whose edges are directed from the parent to the child, the task is to count the number of strictly increasing and decreasing paths. Note: A path starts at the root and ends at any leaf. Examples: Input: N = 6tree = 6 / \ 4 7 \ / \ 5 6 8Output: 10 8Explanation:
12 min read
Find the length of maximum path in given matrix for each index
Given a binary square matrix of characters having size N x N such that 1 represents land and 0 represents water, the task is to find the longest straight-line path a person can travel on land without falling into water or outside for each cell (i, j). The straight line can be either horizontal, vert
15+ min read