LeetCode107:Binary Tree Level Order Traversal II
阿新 • • 發佈:2018-12-22
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] ]
LeetCode:連結
# 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 [] curStack = [root] result = [] while curStack: '''列印當前行''' res = [] '''儲存下一行''' nextStack = [] for i in curStack: res.append(i.val) if i.left: nextStack.append(i.left) if i.right: nextStack.append(i.right) result.insert(0, res) '''將儲存的下一行直接賦值給新的要遍歷的內容 也可以用pop 然後直接新增到curStack中''' curStack = nextStack return result