首页 > 试题广场 >

从下到上打印二叉树

[编程题]从下到上打印二叉树
  • 热度指数:1869 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一棵二叉树,返回齐自底向上的层序遍历。

数据范围:二叉树上节点数满足 ,二叉树上的值满足

样例图:

示例1

输入

{1,2,3,4,#,5,6}

输出

[[4,5,6],[2,3],[1]]

说明

如题面图示 
示例2

输入

{1,2}

输出

[[2],[1]]

说明:本题目包含复杂数据结构TreeNode,点此查看相关信息
class Solution:
    def levelOrderBottom(self , root: TreeNode) -> List[List[int]]:
        # write code here
        q=[root]
        all_res=[]
        while q:
            size=len(q)
            res=[]
            while size>0:
                cur=q.pop(0)
                res.append(cur.val)
                if cur.left:
                    q.append(cur.left)
                if cur.right:
                    q.append(cur.right)
                size-=1
            all_res.append(res)
        return all_res[::-1]

发表于 2022-01-19 07:07:38 回复(0)