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 nBecause traversal all nodes, time complexity = , space complexity =
class Solution:
def countNodes(self, root: TreeNode) -> int:
# BFS
# edge case
if root == None:
return 0
queue = [root]
n = 0
while len(queue) != 0:
l = len(queue)
for i in range(l):
root = queue.pop(0)
n = n + 1
if root.left != None:
queue.append(root.left)
if root.right != None:
queue.append(root.right)
return nBecause traversal all nodes, time complexity = , space complexity =
Time complexity = , space complexity = . This is the worst case, generally it's not necessary to traversal all nodes.
Be careful with two points:
Height of left subtree is always to traversal left child, Height of right subtree is always to traversal right child. Because we want to find
maxheight of left subtree andminheight of right subtree.
class Solution:
def countNodes(self, root: TreeNode) -> int:
# edge case
if root == None:
return 0
# regular case
left = self.leftHeight(root.left)
right = self.rightHeight(root.right)
if left == right:
n = pow(2, left+1) - 1
else:
n = 1 + self.countNodes(root.left) + self.countNodes(root.right)
return n
def leftHeight(self, root):
# stop condition
if root == None:
return 0
return 1 + self.leftHeight(root.left)
def rightHeight(self, root):
# stop condition
if root == None:
return 0
return 1 + self.rightHeight(root.right)Last updated
Was this helpful?