从上到下打印二叉树
请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
核心思想:判断当前层是第几层,来决定是顺序打印还是逆序打印
/**
* 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>> list = new ArrayList<List<Integer>>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
if(root != null){
queue.add(root);
}
//打印顺序标志,每打印一行就反转一次,true默认从左向右
//如果需要从右向左打印,先保存到栈中,再依次弹出加入到List集合
Boolean flag = true;
while(!queue.isEmpty()){
List<Integer> temp = new ArrayList<Integer>();
if(flag){
//正向打印
for(int i = queue.size(); i > 0; i--){
TreeNode cur = queue.poll();
temp.add(cur.val);
if(cur.left != null){
queue.add(cur.left);
}
if(cur.right != null){
queue.add(cur.right);
}
}
list.add(temp);
flag = !flag;
}else{
//反向打印
Stack<Integer> stack = new Stack<Integer>();
for(int i = queue.size(); i > 0; i--){
TreeNode cur = queue.poll();
stack.push(cur.val);
if(cur.left != null){
queue.add(cur.left);
}
if(cur.right != null){
queue.add(cur.right);
}
}
//出栈,加入到temp里
while(!stack.isEmpty()){
temp.add(stack.pop());
}
flag = !flag;
list.add(temp);
}
}
return list;
}
}
耗时:2ms
优化:使用结果集中的元素个数来判断是第几层,并且使用LinkedList作为temp,LinkedList里有加入到队列头部和尾部的操作,耗时更短
if(list.size() % 2 == 0) tmp.addLast(node.val); // 偶数层 -> 队列头部
else tmp.addFirst(node.val); // 奇数层 -> 队列尾部