Description
Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
sln1
看到题目很直接就想到用广度优先搜索,用递归实现。python代码如下
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root == None:
return []
return self.bfs([root])
def bfs(self, nodes):
if len(nodes) == 0:
return []
branch = []
values = []
for node in nodes:
values.append(node.val)
if node.left != None:
branch.append(node.left)
if node.right != None:
branch.append(node.right)
next_layer_values = self.bfs(branch)
next_layer_values.append(values)
return next_layer_values
每一次递归一个循环,分别记录values和branch数组。values数组记录当前层每个节点的val,branch数组记录当前层的所有子节点。接下来调用bfs方法获取到当前层以下的所有层的遍历结果,再把values数组添加进去并返回。思路十分清晰,但是提交后看结果并不是十分理想,同样是python实现,只超过了10%+的提交。
sln2
参考discussion中一个标题为 C++ 4ms solution 的答案,用python简答复现了一次,提交结果尽然比70%+的结果快。python实现如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root == None:
return []
depth = self.depth(root)
return self.levelOrder([[] for _ in xrange(depth)], root, depth - 1)
def levelOrder(self, ans, node, depth):
if node is None:
return ans
ans[depth].append(node.val)
ans = self.levelOrder(ans, node.left, depth - 1)
ans = self.levelOrder(ans, node.right, depth - 1)
return ans
def depth(self, node):
if node is None:
return 0
return max(self.depth(node.left), self.depth(node.right)) + 1
一开始并不是很理解为什么这个实现会比我的第一种实现更快,思考一下之后发现,第一种实现方法里面很显然是有一个循环的。在这个循环中,我们遍历了一遍父节点,并把子节点都压进一个数组中,相当于也遍历了一遍子节点。当我们把这个子节点数组丢进下一次递归时,又会再遍历一次,所以实际上等于所有子节点都遍历了两次,所以速度上就慢了很多