Iterative program to Calculate Size of a tree | Node Structure ; Return size of tree ; if tree is empty it will return 0 ; Using level order Traversal . ; when the queue is empty : the pop ( ) method returns null . ; Increment count ; Enqueue left child ; Increment count ; Enqueue right child ; creating a binary tree and entering the nodes
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 sizeoftree ( root ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return 0 NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE count = 1 NEW_LINE while ( len ( q ) != 0 ) : NEW_LINE INDENT root = q . pop ( 0 ) NEW_LINE if ( root . left ) : NEW_LINE INDENT count += 1 NEW_LINE q . append ( root . left ) NEW_LINE DEDENT if ( root . right ) : NEW_LINE INDENT count += 1 NEW_LINE q . append ( root . right ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT 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 print ( sizeoftree ( root ) ) NEW_LINE