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

[Tree]102. Binary Tree Level Ord

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

102. Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

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

代码:

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

讨论:

1.挺简单的,考察的遍历树?

相关文章

网友评论

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

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