Problem : https://leetcode.com/problems/count-complete-tree-nodes/
DFS Solution:
Time Complexity = O ( N )
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: TreeNode) -> int:
if not root:
return 0
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
BFS Solution:
Time Complexity = O ( N )
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: TreeNode) -> int:
if not root:
return 0
queue = deque([root])
level = 0
result = 0
while queue:
tmp = deque()
result += len(queue)
while queue:
node = queue.popleft()
if node.left:
tmp.append(node.left)
if node.right:
tmp.append(node.right)
# stop traversal when reach the last level
if len(tmp) < 2 ** level:
return result + len(tmp)
queue = tmp
return result
No comments:
Post a Comment