LeetCode之 107. Binary Tree Level Order Traversal II python

给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

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

    3
   / \
  9  20
    /  \
   15   7

返回其自底向上的层次遍历为:

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

# 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 levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        
        if root == None:
            return []
        temp=[]
        res=[]
        stack=[]
        n=1
        stack.append(root) 
        while stack:                #stack用来遍历树的所有元素,temp存储每层的元素,n判断该层元素是否处理完
            node=stack.pop(0)
            n-=1
            temp+=[node.val]
            if node.left!=None:
                stack.append(node.left)
            if node.right!=None:
                stack.append(node.right)
            if n == 0:
                res.insert(0,temp)
                temp=[]
                n=len(stack)
        return res

猜你喜欢

转载自blog.csdn.net/weixin_40748006/article/details/80075273