zoukankan      html  css  js  c++  java
  • 树的遍历 | 二叉树的倒序层次遍历

    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
    
  • 相关阅读:
    hdoj5813【构造】
    Codeforces645B【树状数组求逆序数】
    pojcoin【未完待续】
    hdoj5818【模拟】
    poj2385【基础DP】
    poj3069【贪心,水】
    谦虚
    poj3617【贪心】
    poj2229【完全背包-规律Orz...】
    poj3176【简单DP】
  • 原文地址:https://www.cnblogs.com/xmxj0707/p/10381116.html
Copyright © 2011-2022 走看看