"""
QUESTION:
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]
]

ANSWER:
dfs, bfs
"""
# Definition for a  binary tree node
# class TreeNode:
#     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 = []
        if not root:
            return res
        queue = [root]
        while len(queue):
            ll = [] #last level
            cur = []
            for q in queue:
                if q.left: ll.append(q.left)
                if q.right: ll.append(q.right)
                cur.append(q.val)
            res = [cur] + res
            queue = ll
        return res

    def levelOrder_2(self, root):
        if not root:
            return []
        queue = [root]
        res = []
        last = 0
        while last != len(queue):
            n = len(queue)-last
            cur = []
            for i in xrange(n):
                node = queue[last]
                last += 1
                cur.append(node.val)
                if node.left: queue.append(node.left)
                if node.right: queue.append(node.right)
            res = [cur] + res
        return res

    def levelOrder_3(self, root):
        def dfs(root,level):
            if root == None:
                return
            if len(res) <= level:
                res.insert(0,[root.val])
            else:
                res[len(res)-level-1].append(root.val)
            dfs(root.left,level+1)
            dfs(root.right,level+1)
        res = []
        dfs(root,0)
        return res

if __name__ == '__main__':
    print
