222. Count Complete Tree Nodes
# Medium
class Solution:
def countNodes(self, root: TreeNode) -> int:
# DFS
# edge case
if root == None:
return 0
stack = [root]
n = 0
while len(stack) != 0:
root = stack.pop()
n = n + 1
if root.left != None:
stack.append(root.left)
if root.right != None:
stack.append(root.right)
return n
Because traversal all nodes, time complexity = , space complexity =
Last updated
Was this helpful?