- 分类: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.挺简单的,考察的遍历树?
网友评论