LeetCode 107. 二叉树的层次遍历 II (Binary Tree Level Order Traversal II)[简单]

lework · 2020年04月02日 · 最后由 lework 回复于 2020年04月02日 · 107 次阅读

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

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

  3
 / \
9  20
  /  \
 15   7

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

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

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []
        stack = [root]
        res = []
        while stack:
            temp = []
            for i in range(len(stack)):
                cur = stack.pop(0)
                temp.append(cur.val)
                if cur.left:
                    stack.append(cur.left)
                if cur.right:
                    stack.append(cur.right)
            res.append(temp)
        return res[::-1]
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册