- 给定一个二叉树,返回其从下到上的层序遍历(从左到右,从下到上)。
- 用栈来实现DFS,注意要在深搜的时候记录当前的深度。
# 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]]
"""
res = []
stack = [(root, 0)]
while len(stack) > 0:
node, depth = stack.pop()
if node:
if len(res) <= depth:
res.insert(0, [])
res[-(depth+1)].append(node.val)
stack.append((node.right, depth+1))
stack.append((node.left, depth+1))
return res