Count half nodes in a Binary tree ( Iterative and Recursive ) | A node structure ; Function to get the count of half Nodes in a binary tree ; 2 / \ 7 5 \ \ 6 9 / \ / 1 11 4 Let us create Binary Tree shown in above example
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 gethalfCount ( root ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = 0 NEW_LINE if ( root . left == None and root . right != None ) or ( root . left != None and root . right == None ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT res += ( gethalfCount ( root . left ) + gethalfCount ( root . right ) ) NEW_LINE return res NEW_LINE DEDENT root = newNode ( 2 ) NEW_LINE root . left = newNode ( 7 ) NEW_LINE root . right = newNode ( 5 ) NEW_LINE root . left . right = newNode ( 6 ) NEW_LINE root . left . right . left = newNode ( 1 ) NEW_LINE root . left . right . right = newNode ( 11 ) NEW_LINE root . right . right = newNode ( 9 ) NEW_LINE root . right . right . left = newNode ( 4 ) NEW_LINE print ( gethalfCount ( root ) ) NEW_LINE