首页
学习
活动
专区
圈层
工具
发布

【python-leetcode102-树的宽度遍历】二叉树的层次遍历

问题描述:

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

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

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

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

代码:

代码语言:javascript
复制
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []
        queue=[root]
        res=[]
        while queue:
            tmp=[] 
            for i in range(len(queue)):
                node=queue.pop(0)
                tmp.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            res.append(tmp)
        return res
下一篇
举报
领券