我是靠谱客的博主 狂野外套,这篇文章主要介绍107二叉树的层序遍历2,现在分享给大家,希望可以做个参考。

107二叉树的层序遍历2

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

复制代码
1
2
3
输入:root = [3,9,20,null,null,15,7] 输出:[[15,7],[9,20],[3]]
复制代码
1
2
3
输入:root = [1] 输出:[[1]]
复制代码
1
2
3
输入:root = [] 输出:[]
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]: #非递归 results = [] if not root:return results from collections import deque que = deque([root]) while que: result = [] for i in range(len(que)): cur = que.popleft() result.append(cur.val) if cur.left: que.append(cur.left) if cur.right: que.append(cur.right) results.append(result) return results[::-1] #递归 # res = [] # if not root:return [] # def helper(root, depth): # if len(res) == depth:res.append([]) # res[depth].append(root.val) # if root.left: # helper(root.left, depth+1) # if root.right: # helper(root.right,depth+1) # helper(root, 0) # return res[::-1]

最后

以上就是狂野外套最近收集整理的关于107二叉树的层序遍历2的全部内容,更多相关107二叉树内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部