zoukankan      html  css  js  c++  java
  • LeetCode--107--二叉树的层次遍历II

    问题描述:

    给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

    例如:
    给定二叉树 [3,9,20,null,null,15,7],

        3
       / 
      9  20
        /  
       15   7
    

    返回其自底向上的层次遍历为:

    [
      [15,7],
      [9,20],
      [3]
    ]

    方法1:以为二叉树的层次遍历为依托,把该层的值append到temp_list中,当front等于last时,表明当前层遍历结束,res_list.append(temp_list).
     1 class Solution(object):
     2     def levelOrderBottom(self, root):
     3         """
     4         :type root: TreeNode
     5         :rtype: List[List[int]]
     6         """
     7         if not root:
     8             return []
     9         if not root.left and not root.right:
    10             return [[root.val]]
    11         rear = -1
    12         last = 0
    13         front = -1
    14         b_list = []
    15         temp_list =[]
    16         res_list = []
    17         rear += 1
    18         b_list.append(root)
    19         res_list.append([root.val])
    20         while front < rear:
    21             
    22             front += 1
    23             p =b_list.pop(0)
    24             if p.left :
    25                 rear += 1
    26                 b_list.append(p.left)
    27                 temp_list.append(p.left.val)
    28             if p.right :
    29                 rear += 1
    30                 b_list.append(p.right)
    31                 temp_list.append(p.right.val)
    32             if last == front:
    33                 res_list.append(temp_list)
    34                 last = rear
    35                 temp_list = []
    36         res_list.pop()
    37         res_list = res_list[::-1]
    38         return res_list
    简洁版:
     1 class Solution(object):
     2     def levelOrderBottom(self, root):
     3         """
     4         :type root: TreeNode
     5         :rtype: List[List[int]]
     6         """
     7         if not root:return []
     8         s = [root]
     9         res=[]
    10         while s:
    11             l=[]
    12             for i in range(len(s)):
    13                 n = s.pop(0)
    14                 l.append(n.val)
    15                 if n.left:
    16                     s.append(n.left)
    17                 if n.right:  
    18                     s.append(n.right)
    19             res.append(l)
    20         return res[::-1]

    2018-09-09 15:10:44






  • 相关阅读:
    Git ---游离状态下的commit 分支切换与找回,commit之后无法找到历史记录
    mybatis异常invalid comparison: java.util.Date and java.lang.String
    Spring的注解@Qualifier
    Spring @Bean注解的使用
    Java的IO系统
    linkin大话面向对象--GC和jar包
    linkin大话面向对象--闭包和回调
    linkin大话面向对象--内部类
    linkin大话面向对象--枚举
    linkin大话面向对象--接口
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/9613736.html
Copyright © 2011-2022 走看看