LeetCode#102.二叉树的层次遍历 (python解题----BFS)

问题描述:

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

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

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal

 思路:

因为是将二叉树的元素逐层输出。所以使用BFS解题会很方便。

但由于要将每一层的元素分开,放至res中。因此在BFS的基础上,对于每一层的元素,需要增加存储同一层元素的操作。

对于树:[3,9,20,null,null,15,7]

队列处理的过程如下:

先将根节点加入队列,再取出

扫描二维码关注公众号,回复: 12684017 查看本文章

第一次队列:3

再将根节点的左右节点元素加入队列,再取出:
第二次队列:9 20

再将9和12的左右节点元素加入队列(先处理左子树,再处理右子树)

第三次队列:15 7

因此只需要计算当前队列的长度,循环依次将队列的元素加入temp中,并将二叉树的下一层元素加入队列。直到队列为空。

Python版本:

# 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]]
        """
        res = []
        if root == None:
            return res  #这里要返回res 而不能只return 否则会有输入为[]的用例无法通过
        queue = []
        queue.append(root)
        temp = []
        while queue:
            temp = []
            size = len(queue)
            for i in range(size):
                currentNode = queue.pop(0)
                temp.append(currentNode.val)
                if currentNode.left:
                    queue.append(currentNode.left)
                if currentNode.right:
                    queue.append(currentNode.right)
            res.append(temp)
        return res

猜你喜欢

转载自blog.csdn.net/paranior/article/details/104467085