美文网首页
[Tree]107. Binary Tree Level Ord

[Tree]107. Binary Tree Level Ord

作者: 野生小熊猫 | 来源:发表于2019-02-22 22:35 被阅读0次
    • 分类:Tree
    • 时间复杂度: O(n) 这种把树的节点都遍历一遍的情况时间复杂度为O(n)
    • 空间复杂度: O(h) 树的节点的深度

    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:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        
        dict_={}
        
        def levelOrderBottom(self, root: 'TreeNode') -> 'List[List[int]]': 
            res=[]
            
            if root==None:
                return res
            
            self.dict_={}
            depth=self.helper(root,0)
            
            while depth>=0:
                res.append(self.dict_[depth])
                depth-=1
            return res
        
        def helper(self,root,level):
            
            if root==None:
                return level-1
            if level not in self.dict_:
                self.dict_[level]=[]
            self.dict_[level].append(root.val)
            return  max(self.helper(root.left,level+1),self.helper(root.right,level+1))
    

    讨论:

    1.这道题是104和102的combine,一边返回层数,一边加到list里面,还算比较简单的题?

    相关文章

      网友评论

          本文标题:[Tree]107. Binary Tree Level Ord

          本文链接:https://www.haomeiwen.com/subject/fowyyqtx.html