Longest consecutive sequence in Binary tree | A utility class to create a node ; 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 newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def longestConsecutiveUtil ( root , curLength , expected , res ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . data == expected ) : NEW_LINE INDENT curLength += 1 NEW_LINE DEDENT else : NEW_LINE INDENT curLength = 1 NEW_LINE DEDENT res [ 0 ] = max ( res [ 0 ] , curLength ) NEW_LINE longestConsecutiveUtil ( root . left , curLength , root . data + 1 , res ) NEW_LINE longestConsecutiveUtil ( root . right , curLength , root . data + 1 , res ) NEW_LINE DEDENT def longestConsecutive ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = [ 0 ] NEW_LINE longestConsecutiveUtil ( root , 0 , root . data , res ) NEW_LINE return res [ 0 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 6 ) NEW_LINE root . right = newNode ( 9 ) NEW_LINE root . right . left = newNode ( 7 ) NEW_LINE root . right . right = newNode ( 10 ) NEW_LINE root . right . right . right = newNode ( 11 ) NEW_LINE print ( longestConsecutive ( root ) ) NEW_LINE DEDENT