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]
]

解题方法

将level order的解法改一下,在最后reverse,或者在插入到result里的时候插入到最前面

Solution

from collections import deque
# 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 not root:
            return []
        queue = deque()
        result = []
        curList = []
        curNum = 1
        nextNum = 0
        queue.append(root)
        while queue:
            cur = queue.popleft()
            curNum -= 1
            curList.append(cur.val)
            if cur.left:
                queue.append(cur.left)
                nextNum += 1
            if cur.right:
                queue.append(cur.right)
                nextNum += 1
            if curNum == 0:
                curNum = nextNum
                nextNum = 0
                result.append(list(curList)) # or insert(0, list(curList))
                curList = []

        result.reverse()  # if insert at 0, no need 
        return result

Reference