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]
]
以下代码中的stack变量应该命名为queue,以免误导
Code
# 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]]
"""
return self.getList([root], [], 1)
def getList(self, stack, res, cnt):
nodes = []
flag = True #标记该层是否都是空节点
if len(stack) == 0:
return res
for i in range(0, cnt):
nodes += [stack.pop(0)]
newRes = []
for j in nodes:
if j == None:
stack += [None, None]
else:
flag = False
stack += [j.left]
stack += [j.right]
newRes += [j.val]
if not flag:
res = [newRes] + res
return self.getList(stack, res, cnt * 2)
else:
return res
第一版,应该是正确的,但是会超时。观察了下,有改进的余地。
Code
# 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]]
"""
stack, res, cnt = [root], [], 1
while not len(stack) == 0:
flag = True #标记该层是否都是空节点
nodes = []
for i in range(0, cnt):
node = stack.pop(0)
if node == None:
stack += [None, None]
else:
flag = False
stack += [node.left, node.right]
nodes += [node.val]
if flag:
return res
else:
res = [nodes] + res
cnt *= 2
return res
第二版,更加精简了,但还是超时。观察了下超时用例,树有很多层,同时很多null,但是我的代码里还是将空节点存到stack里了,所以耗费了时间去处理。下个版本的代码改进点就是从stack中去掉空节点了。
Code
# 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 []
stack, res = [root], []
while not len(stack) == 0:
level = []
temp = []
for node in stack:
if not node.left == None:
temp += [node.left]
if not node.right == None:
temp += [node.right]
level += [node.val]
res = [level] + res
stack = temp
return res
这里遇到个debug了很久的问题,当level = temp = []这么初始化的时候一直有bug,结果发现是自己没有掌握清楚语法。a = b = []的时候,a和b指向的是同一个地址,二者谁修改了该处的值,另一方都能读出来。而a = [], b = []这两者就没有关系了。
看了下别人的算法,一种是我这样的BFS,另一种就是DFS,利用二维数组来存储信息。