zoukankan      html  css  js  c++  java
  • leetcode 107. 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,null,null,15,7],

        3
       / 
      9  20
        /  
       15   7
    

    return its bottom-up level order traversal as:

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

    # 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 []
            q = [root]
            ans = []
            while q:
                ans.append([n.val for n in q])
                q = [n for node in q for n in (node.left, node.right) if n]           
            return ans[::-1]        

    上面解法是层序遍历,使用先序遍历,递归:

    # 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]]
            """        
            def dfs(node, paths, depth):
                if not node: return
                if len(paths) == depth:
                    paths.append([])                
                paths[depth].append(node.val)
                dfs(node.left, paths, depth+1)
                dfs(node.right, paths, depth+1)
            ans = []
            dfs(root, ans, 0)
            return ans[::-1]                        
    
  • 相关阅读:
    Unity NPOI 无法读取xlsx
    spring源码之—Assert.notNull
    手工Ghost安装系统
    一键GHOST优盘版安装XP/win7系统
    oncontextmenu事件
    Maven 常用配置
    U盘装win7系统
    eval json ajax
    Maven--pom.xml 配置详解
    Maven 构建
  • 原文地址:https://www.cnblogs.com/bonelee/p/8729209.html
Copyright © 2011-2022 走看看