欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

102. 二叉树的层次遍历

程序员文章站 2022-03-03 10:35:53
...

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

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

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]

思路:树的层次遍历,很自然的就想到使用BFS。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []
        
        res = []
        nodeList = [root]
        
        while nodeList:
            # 每次循环置空
            nodeNext = []
            resTemp = []
            
            for x in nodeList:
                # 暂存一层的值
                resTemp.append(x.val)
                if x.left:
                    nodeNext.append(x.left)
                if x.right:
                    nodeNext.append(x.right)
            
            res.append(resTemp)
            nodeList = nodeNext

        return res