How to determine if a binary tree is height | A binary tree Node ; function to check if tree is height - balanced or not ; Base condition ; for left and right subtree height allowed values for ( lh - rh ) are 1 , - 1 , 0 ; if we reach here means tree is not height - balanced tree ; function to find height of binary tree ; base condition when binary tree is empty ; If tree is not empty then height = 1 + max of left height and right heights ; Driver function to test the above function
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def isBalanced ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return True NEW_LINE DEDENT lh = height ( root . left ) NEW_LINE rh = height ( root . right ) NEW_LINE if ( abs ( lh - rh ) <= 1 ) and isBalanced ( root . left ) is True and isBalanced ( root . right ) is True : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def height ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT return max ( height ( root . left ) , height ( root . right ) ) + 1 NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . left . left . left = Node ( 8 ) NEW_LINE if isBalanced ( root ) : NEW_LINE INDENT print ( " Tree ▁ is ▁ balanced " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Tree ▁ is ▁ not ▁ balanced " ) NEW_LINE DEDENT