Maximum Consecutive Increasing Path Length in Binary Tree | C ++ Program to find Maximum Consecutive Path Length in a Binary Tree ; To represent a node of a Binary Tree ; Create a new Node and return its address ; Returns the maximum consecutive Path Length ; Get the value of Current Node The value of the current node will be prev Node for its left and right children ; 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 ; 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 ; Find length of the maximum path under subtree rooted with this node ( The path may or may not include this node ) ; Take the maximum previous path and path under subtree rooted with this node . ; A wrapper over maxPathLenUtil ( ) . ; Return 0 if root is NULL ; Else compute Maximum Consecutive Increasing Path Length using maxPathLenUtil . ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { Node * left , * right ; int val ; } ; Node * newNode ( int val ) { Node * temp = new Node ( ) ; temp -> val = val ; temp -> left = temp -> right = NULL ; return temp ; } int maxPathLenUtil ( Node * root , int prev_val , int prev_len ) { if ( ! root ) return prev_len ; int cur_val = root -> val ; if ( cur_val == prev_val + 1 ) { return max ( maxPathLenUtil ( root -> left , cur_val , prev_len + 1 ) , maxPathLenUtil ( root -> right , cur_val , prev_len + 1 ) ) ; } int newPathLen = max ( maxPathLenUtil ( root -> left , cur_val , 1 ) , maxPathLenUtil ( root -> right , cur_val , 1 ) ) ; return max ( prev_len , newPathLen ) ; } int maxConsecutivePathLength ( Node * root ) { if ( root == NULL ) return 0 ; return maxPathLenUtil ( root , root -> val - 1 , 0 ) ; } 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 ; }