Python教程

leetcode-python-二叉树的层序遍历

本文主要是介绍leetcode-python-二叉树的层序遍历,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

就是BFS,同时把每层的值作为列表保存

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        result = list()
        layer = list()
        layer_val = list()
        size = 0
        if not root:
            return  []
        layer_val.append(root.val)
        result.append(layer_val)
        layer.append(root)
        while layer:
            size = len(layer)
            layer_val = list()
            while size > 0:
                temp = layer[0]
                if temp.left:
                    layer.append(temp.left)
                    layer_val.append(temp.left.val)
                if temp.right:
                    layer.append(temp.right)
                    layer_val.append(temp.right.val)
                size -= 1
                del layer[0]
            if layer_val == []:
                return result
            result.append(layer_val)
        return result

 

这篇关于leetcode-python-二叉树的层序遍历的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!