1. Use general recursion to obtain
1 def Getnodenums (head): 2 if not Head: 3 return 0 4 Lnums = getnodenums (head.left)5 rnums = getnodenums (head.right)6 return lnums + rnums + 1
2. Recursive (Time complexity O (LOGN*LOGN)) with full binary tree characteristics
1 #using the full binary tree feature, recursive time complexity is used: O (LOGN*LOGN)2 #The total number of tree nodes with two forks is 2**n-13 defNodenums (head):4 if notHead:5 return06 returnBS (head, 1, Mostleftlevel (head, 1)) 7 8 #total number of nodes in the current node9 defBS (node, level, height):Ten ifLevel = =Height: One return1 A #If the right child node of the current node equals the parent node depth minus one, that is, the left subtree of the current node is full two-tree - ifMostleftlevel (node.right, level+1) = =Height: - #Returns the number of left child tree nodes + parent node + right subtree node the return2** (Height-level) + BS (Node.right, level+1, height) - Else: - #If the right child node depth is not equal to the parent node depth minus one, then this tree is a complete binary tree, that is, the right subtree is full two tree - #Returns the number of right subtree nodes + parent node + Left child tree node + return2** (HEIGHT-LEVEL-1) + BS (Node.left, level+1, height) - + #to solicit the depth of the current node according to the full binary tree A defmostleftlevel (node, level): at whilenode: -Level + = 1 -node =Node.left - returnLevel-1
The total number of nodes for a complete binary tree python implementation