跳到主要内容

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,#,#,15,7},

    3
/ \
9 20
/ \
15 7

return its level order traversal as:

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

分析

从题目所求的目标来看,毫无疑问用广搜。

代码

迭代版

# Binary Tree Level Order Traversal
# 迭代版,时间复杂度O(n),空间复杂度O(1)
from collections import deque

class Solution:
def levelOrder(self, root):
result = []
current = deque()
next = deque()

if root:
current.append(root)

while current:
level = [] # elments in one level
while current:
node = current.popleft()
level.append(node.val)
if node.left:
next.append(node.left)
if node.right:
next.append(node.right)
result.append(level)
# swap
current, next = next, current

return result

递归版

// Binary Tree Level Order Traversal
// 递归版,时间复杂度O(n),空间复杂度O(n)
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
traverse(root, 1, result);
return result;
}

void traverse(TreeNode root, int level,
List<List<Integer>> result) {
if (root == null) return;

if (level > result.size())
result.add(new ArrayList<>());

result.get(level-1).add(root.val);
traverse(root.left, level+1, result);
traverse(root.right, level+1, result);
}
}

相关题目