【python-leetcode107-树的宽度遍历】二叉树的层次遍历Ⅱ

时间:2022-07-23
本文章向大家介绍【python-leetcode107-树的宽度遍历】二叉树的层次遍历Ⅱ,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

问题描述:

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

例如: 给定二叉树 [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:
#     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:
            tmp=[]
            for i in range(len(stack)):
                t=stack.pop(0)
                tmp.append(t.val)
                if t.left:
                    stack.append(t.left)
                if t.right:
                    stack.append(t.right)
            res.insert(0,tmp)
        return res

与之前层次遍历一致,之后最后每次将tmp插入到res的首位即可。