原題
給出一棵二叉樹,返回其節點值從底向上的層次序遍歷(按從葉節點所在層到根節點所在的層遍歷,然后逐層從左往右遍歷)
給出一棵二叉樹 {3,9,20,#,#,15,7}
3
/ \
9 20
/ \
15 7
按照從下往上的層次遍歷為:
[
[15,7],
[9,20],
[3]
]
解題思路
- 本題與[Binary Tree Level Order Traversal I]一樣,同樣使用一個queue解決,只是在生成result的時候不是
append
而是insert(0, temp)
- 每次從見面加入
temp
結果
完整代碼
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import Queue
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
result = []
MyQueue = Queue.Queue()
MyQueue.put(root)
while not MyQueue.empty():
temp = []
size = MyQueue.qsize()
for i in range(size):
node = MyQueue.get()
if node.left:
MyQueue.put(node.left)
if node.right:
MyQueue.put(node.right)
temp.append(node.val)
result.insert(0, temp)
return result