222. Count Complete Tree Nodes
# Medium
Three approaches:
DFS traversal all nodes, and count at the same time
BFS traversal all nodes, and count at the same time
Strategy:
If
height(root.left) = height(root.right)
, then n=2height+1If
height(root.left) > height(root.right)
, thenn = 1+nums(root.left)+nums(root.left)
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 = O(n) , space complexity = O(n)
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 n
Because traversal all nodes, time complexity = O(n) , space complexity = O(n)
Time complexity = O(n) , space complexity = O(1) . This is the worst case, generally it's not necessary to traversal all nodes.
Be careful with two points:
1+21+22+...+2n=2n+1−1
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
max
height of left subtree andmin
height 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?