BFS

题目列表

  • Binary Tree Level Order Traversal
    • 两个queue
    • 递归
  • Binary Tree Level Order Traversal II
  • Binary Tree ZigZag level order Traversal
  • Binary Tree Right Side View

  • leetcode bfs

模板

from collections import deque
def bfs(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        queue = deque()
        result = []
        queue.append(root)
        while queue:
            size = len(queue) # the size if the num of node in current level
            for i in range(size): 
                cur = queue.popleft()
                if cur.left:
                    queue.append(cur.left)
                if cur.right:
                    queue.append(cur.right)
        return result

Reference