剑指 Offer 32 - II. 从上到下打印二叉树 II
题目
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
提示:
节点总数 <= 1000
题解
层次遍历,用变量存储下一层的节点数量即可
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null)
return new ArrayList<List<Integer>>();
ArrayList<List<Integer>> lists = new ArrayList<>();
ArrayDeque<TreeNode> q = new ArrayDeque<>();
q.add(root);
int thisCount = 1;
int nextCount = 0;
ArrayList<Integer> list = new ArrayList<>();
while(!q.isEmpty()){
if(thisCount > 0){
TreeNode t = q.poll();
list.add(t.val);
thisCount --;
if(t.left != null){
q.add(t.left);
nextCount ++;
}
if(t.right != null){
q.add(t.right);
nextCount ++;
}
}else{
lists.add(list);
thisCount = nextCount;
nextCount = 0;
list = new ArrayList<>();
}
}
lists.add(list);
return lists;
}
}