- 使用双端队列实现从last 加入 或者first加入 实现逆序
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
if (pRoot == null){
return new ArrayList<ArrayList<Integer>>();
}
Deque<TreeNode> deque = new LinkedList<TreeNode>();
deque.offer(pRoot);
boolean isOdd = false;
while (!deque.isEmpty()){
int n = deque.size();
isOdd = !isOdd;
Deque<Integer> arrDeque = new LinkedList<Integer>();
for (int i = 0; i < n; i++) {
TreeNode temp = deque.poll();
/*正向加入*/
if (isOdd){
arrDeque.offerLast(temp.val);
}else {
arrDeque.offerFirst(temp.val);
}
if (temp.left != null){
deque.offer(temp.left);
}
if (temp.right != null){
deque.offer(temp.right);
}
}
res.add(new ArrayList<>(arrDeque));
}
return res;
}
}