剑指 Offer 32 - II. 从上到下打印二叉树 II
题目描述
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
示例:
给定二叉树: [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7
返回其层次遍历结果:
[ [3], [9,20], [15,7] ]
数据限制:
节点总数 <= 1000
思路
该题和上一题基本相同,只要将最后的列表合并取消即可
时间复杂度:O(n)
空间复杂度:O(n)
代码
import java.util.*;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List list = new ArrayList();
ArrayList<Integer> lis[] = new ArrayList[2005];
int top = 0;
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null){
return list;
}
for (int i = 0; i <= 2000; i++){
lis[i] = new ArrayList();
}
dfs(root, 1);
for (int i = 1; i <= top; i++){
list.add(lis[i]);
}
return list;
}
void dfs(TreeNode p, int x){
top = Math.max(top, x);
lis[x].add(p.val);
if (p.left != null){
dfs(p.left, x + 1);
}
if (p.right != null){
dfs(p.right, x + 1);
}
}
}