Longest consecutive sequence in Binary tree | A binary tree node has data , pointer to left child and a pointer to right child ; Utility method to return length of longest consecutive sequence of tree ; if root data has one more than its parent then increase current length ; update the maximum by current length ; recursively call left and right subtree with expected value 1 more than root data ; method returns length of longest consecutive sequence rooted at node root ; call utility method with current length 0 ; Driver code
class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class Result { int res = 0 ; } class BinaryTree { Node root ; private void longestConsecutiveUtil ( Node root , int curlength , int expected , Result res ) { if ( root == null ) return ; if ( root . data == expected ) curlength ++ ; else curlength = 1 ; res . res = Math . max ( res . res , curlength ) ; longestConsecutiveUtil ( root . left , curlength , root . data + 1 , res ) ; longestConsecutiveUtil ( root . right , curlength , root . data + 1 , res ) ; } int longestConsecutive ( Node root ) { if ( root == null ) return 0 ; Result res = new Result ( ) ; longestConsecutiveUtil ( root , 0 , root . data , res ) ; return res . res ; } 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 ) ) ; } }