102. Binary Tree Level Order Tra
2016-08-05 本文已影响9人
oo上海
102. Binary Tree Level Order Traversal
题目:
https://leetcode.com/problems/binary-tree-level-order-traversal/
难度:
Easy
我觉得并不easy
两种做法,利用curLevel和nextLevel来记录,然后按层append.
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
if root == None: return []
curLevel = [root]
while curLevel:
nextLevel = []
tmpRes = []
for node in curLevel:
tmpRes.append(node.val)
if node.left: nextLevel.append(node.left)
if node.right: nextLevel.append(node.right)
res.append(tmpRes)
curLevel = nextLevel
return res
第二种做法:
class Solution:
# @param root, a tree node
# @return a list of lists of integers
def preorder(self, root, level, res):
if root:
if len(res) < level+1: res.append([])
res[level].append(root.val)
self.preorder(root.left, level+1, res)
self.preorder(root.right, level+1, res)
def levelOrder(self, root):
res=[]
self.preorder(root, 0, res)
return res
用递归来记录每一层,需要更加学习,不算easy