python_leetcode102. 二叉树的层次遍历

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

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

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

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

先进先出

# 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 root is None:
            return []
        stack = [root]
        list_sum = []
        while stack:         # 设置none出
            list = []                                   #出栈
            for i in range(len(stack)):      #每一层
                cur = stack.pop(0)
                list.append(cur.val)
                if cur.left:                        
                    stack.append(cur.left)      #入栈
                if cur.right:
                    stack.append(cur.right)
            list_sum.append(list)
        return list_sum

猜你喜欢

转载自blog.csdn.net/AntiZheng/article/details/82589587