Maximum Consecutive Increasing Path Length in Binary Tree | Java 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
import java . util . * ; class GfG { static class Node { Node left , right ; int val ; } static Node newNode ( int val ) { Node temp = new Node ( ) ; temp . val = val ; temp . left = null ; temp . right = null ; return temp ; } static int maxPathLenUtil ( Node root , int prev_val , int prev_len ) { if ( root == null ) return prev_len ; int cur_val = root . val ; if ( cur_val == prev_val + 1 ) { return Math . max ( maxPathLenUtil ( root . left , cur_val , prev_len + 1 ) , maxPathLenUtil ( root . right , cur_val , prev_len + 1 ) ) ; } int newPathLen = Math . max ( maxPathLenUtil ( root . left , cur_val , 1 ) , maxPathLenUtil ( root . right , cur_val , 1 ) ) ; return Math . max ( prev_len , newPathLen ) ; } static int maxConsecutivePathLength ( Node root ) { if ( root == null ) return 0 ; return maxPathLenUtil ( root , root . val - 1 , 0 ) ; } 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 ) ) ; } }