Skip to the content.

leetcode [102] 二叉树的层次遍历


Contact me:

Blog -> https://cugtyt.github.io/blog/index
Email -> cugtyt@qq.com
GitHub -> Cugtyt@GitHub


给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

例如:

给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]
class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if root is None:
            return []
        stack = [(0, root)]
        result = []
        current = []
        index = 0
        while stack:
            i, head = stack[0]
            if i == index:
                current.append(head.val)
            else:
                index += 1
                result.append(current)
                current = [head.val]
            if head.left:
                stack.append((i + 1, head.left))
            if head.right:
                stack.append((i + 1, head.right))
            stack = stack[1:]
        result.append(current)
        return result