sophryu99 / algorithm

algorithm in python - 4 questions a week
4 stars 1 forks source link

102. Binary Tree Level Order Traversal #31

Open sophryu99 opened 1 year ago

sophryu99 commented 1 year ago

102. Binary Tree Level Order Traversal

  1. Append the root to the deque
  2. For the current level, iterate through all node and pop the root node
from collections import deque
class Solution:
    def levelOrder(self, root):
        if not root: return []
        queue, res = deque([root]), []
        # Append the root to the deque
        while queue:
            # For the current level, iterate through all node and pop the root node
            cur_level, size = [], len(queue)
            for _ in range(size):
                node = queue.popleft()
                # If there is left chid, append to the queue
                if node.left:
                    queue.append(node.left)
                # If there is right chid, append to the queue
                if node.right:
                    queue.append(node.right)
                # Append the current root node's val to the current level array
                cur_level.append(node.val)
            # Append the current level's val to the res
            res.append(cur_level)
        return res

n: number of node