[Lintcode]69. Binary Tree Level Order Traversal/[Leetcode]102. Binary Tree Level Order Traversal
69. Binary Tree Level Order Traversal/102. Binary Tree Level Order Traversal
- 本题难度: Easy/Medium
- Topic: Binary Tree
Description
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
Example
Given binary tree {3,9,20,#,#,15,7},
3
/
9 20
/
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
Challenge
Challenge 1: Using only 1 queue to implement it.
Challenge 2: Use BFS algorithm to do it.
我的代码
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: A Tree
@return: Level order a list of lists of integer
"""
def high(self,root,res,h):
if root is None:
return res
if len(res)<h:
res.append([root.val])
else:
res[h-1].append(root.val)
res = self.high(root.left,res,h+1)
res = self.high(root.right,res,h+1)
return res
def levelOrder(self, root):
# write your code here
if root is None:
return []
return self.high(root,[],1)
思路
深度优先遍历,根据深度确定所在的层数