Find height of a special binary tree whose leaf nodes are connected | Helper function that allocates a new node with the given data and None left and right poers . ; Construct to create a new node ; function to check if given node is a leaf node or node ; If given node ' s ▁ left ' s right is pointing to given node and its right ' s ▁ left ▁ is ▁ pointing ▁ to ▁ the ▁ node ▁ itself ▁ ▁ then ▁ it ' s a leaf ; Compute the height of a tree -- the number of Nodes along the longest path from the root node down to the farthest leaf node . ; if node is None , return 0 ; if node is a leaf node , return 1 ; compute the depth of each subtree and take maximum ; Driver Code ; Given tree contains 3 leaf nodes ; create circular doubly linked list out of leaf nodes of the tree set next pointer of linked list ; set prev pointer of linked list ; calculate height of the tree
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def isLeaf ( node ) : NEW_LINE INDENT return node . left and node . left . right == node and node . right and node . right . left == node NEW_LINE DEDENT def maxDepth ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( isLeaf ( node ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 1 + max ( maxDepth ( node . left ) , maxDepth ( node . right ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . left . left . left = newNode ( 6 ) NEW_LINE L1 = root . left . left . left NEW_LINE L2 = root . left . right NEW_LINE L3 = root . right NEW_LINE L1 . right = L2 NEW_LINE L2 . right = L3 NEW_LINE L3 . right = L1 NEW_LINE L3 . left = L2 NEW_LINE L2 . left = L1 NEW_LINE L1 . left = L3 NEW_LINE print ( " Height ▁ of ▁ tree ▁ is ▁ " , maxDepth ( root ) ) NEW_LINE DEDENT