树的遍历 | 二叉树的倒序层次遍历

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

思路:

先用栈存下来,然后按层次打印即可

class Solution(object):
    def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if root == None:
            return []
        stack = []
        root.level = 0
        queue = [root]
        while len(queue):
            root = queue.pop(0)
            if root:
                stack.append(root)
            if root.right:
                q = root.right
                q.level = root.level + 1
                queue.append(q)
            if root.left:
                q = root.left
                q.level = root.level + 1
                queue.append(q)
        result = []
        temp = []
        flag = None
        while(stack):
            root = stack.pop(-1)
            if flag == None or flag == root.level:
                temp.append(root.val)
                flag = root.level
            else:
                result.append(temp)
                temp = [root.val]
                flag = root.level
        if temp:
            result.append(temp)
        return result
posted @ 2019-02-14 22:29  罗梁  阅读(1130)  评论(0编辑  收藏  举报