Density of Binary Tree in One Traversal | A binary tree node ; Function to compute height and size of a binary tree ; compute height of each subtree ; increase size by 1 ; return larger of the two ; function to calculate density of a binary tree ; To store size ; Finds height and size ; 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 heighAndSize ( node , size ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT l = heighAndSize ( node . left , size ) NEW_LINE r = heighAndSize ( node . right , size ) NEW_LINE size [ 0 ] += 1 NEW_LINE return l + 1 if ( l > r ) else r + 1 NEW_LINE DEDENT def density ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT size = [ 0 ] NEW_LINE _height = heighAndSize ( root , size ) NEW_LINE return size [ 0 ] / _height 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 print ( " Density ▁ of ▁ given ▁ binary ▁ tree ▁ is ▁ " , density ( root ) ) NEW_LINE DEDENT