给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [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):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
result = []
t = [root]
while any(t):
temp = []
length = len(t)
for i in range(length):
node = t.pop(0)
temp.append(node.val)
if node.left:
t.append(node.left)
if node.right:
t.append(node.right)
result.append(temp)
result.reverse()
return result

本文介绍了一种二叉树的遍历方法——自底向上的层次遍历,通过实例详细解释了如何从叶子节点开始,逐层向上进行节点值的遍历,并提供了一个Python实现的示例。
591

被折叠的 条评论
为什么被折叠?



