将父节点放入队列
取出的时候 先判断是否有孩子节点 有就放入队列中
输出的时候 判断层数的奇偶
https://www.nowcoder.com/practice/47e1687126fa461e8a3aff8632aa5559?tpId=190&tqId=35183&rp=1&ru=%2Fta%2Fjob-code-high-rd&qru=%2Fta%2Fjob-code-high-rd%2Fquestion-ranking&tab=answerKey
public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
if (pRoot == null) {
return ans;
}
Queue<TreeNode> list = new LinkedList<>();
int num = 0; //记录当前是多少层
list.add(pRoot);
while (list != null && list.size() != 0) {
int count = list.size(); //放了几个节点
ArrayList<Integer> res = new ArrayList<>();
while (count != 0) { //输出一个父节点 就把左右孩子节点放入到队列中
TreeNode node = list.poll();
res.add(node.val);
if (node.left != null) {
list.add(node.left);
}
if (node.right != null) {
list.add(node.right);
}
count--; //记录放了几个节点
}
num++; //记录当前是多少层
if (num % 2 == 0) { //偶数层 从右往左
for (int i = 0, j = res.size() - 1; i < j; i++, j--) {
int tem = res.get(i);
res.set(i, res.get(j));
res.set(j, tem);
}
ans.add(res);
} else {
ans.add(res);
}
}
return ans;
}