Source: https: //leetcode-cn.com/problems/count-complete-tree-nodes/
Act one: their own code
Ideas: the beginning of a multi-method to traverse the line, after the improvement, simply traverse to the last line stop, which is determined by the nature of complete binary tree, pay attention to the sequence of binary tree traversal time, there can not be achieved with a stack must with queues in order to ensure that each row are from left to right to traverse, traversing the last line when it can not go wrong
# Execute when used: 124 ms, beat the 29.46% of users in all python3 submission # memory consumption: 20 MB, defeated 98.68% of users in all python3 submission class Solution: DEF countNodes (Self, root: TreeNode) -> int: stack = [] stack_next = [] level = 0 if root is None: return 0 stack_next.append(root) while stack_next: stack = stack_next stack_next = [] L = len (Stack) # non-empty list to POP () the while Stack: # noted here is not a queue stack, in order to ensure that each traversal from left to right are A = stack.pop (0) IF a: stack_next.append(a.right) stack_next.append(a.left) # Event of a node is empty, indicating that the last line, and returns the result directly calculates the else : return int (len (stack_next) / 2) + (2 ** (. 1-Level)) -. 1 Level + = 1 # original code is time-consuming, the last line may be invalid traverse, # return (2 ** (Level-2) - 1 + int (L / 2))