[Tree]107. Binary Tree Level Order Traversal II

  • 分类: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 Order Traversal II)