题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
思路:采用队列的方法,如果是奇数行就正常list,如果是偶数行就反转list再加入集合,反装是直接调用Collections的反转方法就行。
import java.util.ArrayList;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
TreeNode head = pRoot;
//队列加数组(不用数组,链表的反装是有对应的函数的)
ArrayList<ArrayList<Integer> > resList = new ArrayList<>();
//null
if (head == null) {
return resList;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(head);
boolean flag = true;
while (!queue.isEmpty()) {
ArrayList<Integer> list = new ArrayList<>();
flag = !flag;
//要将size定义出来,因为queue.poll之后,size是在改变的
int n = queue.size();
for (int i = 0 ; i < n; i++) {
//出队列
TreeNode treeNode = queue.poll();
list.add(treeNode.val);
if (treeNode.left != null) {
queue.offer(treeNode.left);
}
if (treeNode.right != null) {
queue.offer(treeNode.right);
}
}
//根据单双数判断是正序还是倒叙加入到list
if (flag) {
Collections.reverse(list);
}
resList.add(list);
}
return resList;
}
}
剑指offer刷题总结 文章被收录于专栏
本专栏是本人刷剑指offer的记录总结,也欢迎大家评论区留言讨论交流~
