Check if all leaves are at same level | A binary tree node ; Recursive function which check whether all leaves are at same level ; Base Case ; If a tree node is encountered ; When a leaf node is found first time ; Set first leaf found ; If this is not first leaf node , compare its level with first leaf 's level ; If this is not first leaf node , compare its level with first leaf 's level ; The main function to check if all leafs are at same level . It mainly uses checkUtil ( ) ; Let us create the tree as shown in the example
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 checkUtil ( root , level ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return True NEW_LINE DEDENT if root . left is None and root . right is None : NEW_LINE INDENT if check . leafLevel == 0 : NEW_LINE INDENT check . leafLevel = level NEW_LINE return True NEW_LINE DEDENT return level == check . leafLevel NEW_LINE DEDENT return ( checkUtil ( root . left , level + 1 ) and checkUtil ( root . right , level + 1 ) ) NEW_LINE DEDENT def check ( root ) : NEW_LINE INDENT level = 0 NEW_LINE check . leafLevel = 0 NEW_LINE return ( checkUtil ( root , level ) ) NEW_LINE DEDENT root = Node ( 12 ) NEW_LINE root . left = Node ( 5 ) NEW_LINE root . left . left = Node ( 3 ) NEW_LINE root . left . right = Node ( 9 ) NEW_LINE root . left . left . left = Node ( 1 ) NEW_LINE root . left . right . left = Node ( 2 ) NEW_LINE if ( check ( root ) ) : NEW_LINE INDENT print " Leaves ▁ are ▁ at ▁ same ▁ level " NEW_LINE DEDENT else : NEW_LINE INDENT print " Leaves ▁ are ▁ not ▁ at ▁ same ▁ level " NEW_LINE DEDENT