Leetcode 107 Binary Tree Level Order Traversal II

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,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

 

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]
class Solution(object):
    def levelOrderBottom(self, root):
        if not root:
            return []
        stack, ans = [root], []
        while stack:
            temp, stack_new = [], []
            for x in stack:
                temp.append(x.val)
                if x.left:
                    stack_new.append(x.left)
                if x.right:
                    stack_new.append(x.right)
            ans = [temp] + ans
            stack = stack_new
        return ans
 
posted @ 2016-06-01 17:29  lilixu  阅读(206)  评论(0编辑  收藏  举报