剑指 Offer 32 - II. 从上到下打印二叉树 II
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
提示:
节点总数 <= 1000
思路:
相比于简单的按层遍历二叉树,这道题的关键在于 如何记录一层的开始和结尾 或者 一层有多少个元素。
有两种做法,
第一种是记录每一层有多少个元素,while循环一次批量打印一层的元素(见下面代码);
第二种是记录每一层的起始点和终止点,while循环一次只打印一个元素。(等我后面刷到了类似的题,再来补充……)
弹出元素时需要向队列中加入该元素的左孩子、右孩子。
下面的代码是LeetCode大佬写的,巧妙之处在于:用于弹出、记录本层元素的for循环的变量i从高到低取值,如此一来,不必担心在for循环中删除、添加会更改原来queue的大小(即 当前层的元素个数),从而省了一个int型变量size。
/**
* 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) {
List<List<Integer>> ans = new ArrayList<>();
if(root==null){
return ans;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
List<Integer> sub = new ArrayList<>();
for(int i=queue.size();i>0;i--){
TreeNode cur = queue.poll();
sub.add(cur.val);
if(cur.left!=null){queue.add(cur.left);}
if(cur.right!=null){queue.add(cur.right);}
}
ans.add(sub);
}
return ans;
}
}
如果for循环变量i不从高到低变化,那么需要再申请一个变量size来记录 当前层的元素数,如下
/**
* 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) {
List<List<Integer>> ans = new ArrayList<>();
if(root==null){
return ans;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
List<Integer> sub = new ArrayList<>();
int size = queue.size();// !! appply a new variable to record the number of elements in the current level
for(int i=0;i<size;i++){ // !! i starts from 0
TreeNode cur = queue.poll();
sub.add(cur.val);
if(cur.left!=null){queue.add(cur.left);}
if(cur.right!=null){queue.add(cur.right);}
}
ans.add(sub);
}
return ans;
}
}
写法3
不同于上面“使用int型变量size,标记当前层有多少节点”的思路,这里使用TreeNode型变量last
,nextLast
分别记录当前层和下一层的最后一个点,从而达到“换行”的目的,具体代码如下:
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res=new ArrayList<>();
if(root==null) return res;
Queue<TreeNode> queue=new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
List<Integer> level=new ArrayList<>();
int size=queue.size();
for(int i=0;i<size;i++){
TreeNode cur=queue.poll();
level.add(cur.val);
if(cur.left!=null){
queue.offer(cur.left);
}
if(cur.right!=null){
queue.offer(cur.right);
}
}
res.add(level);
}
return res;
}