AcWing打卡活动
《剑指Offer》打卡活动
周三第十一题 之字形打印二叉树
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
* 思路
* 和上题的区别,
* a. 一层从左往右
* b. 一层从右往左
* 所以需要记录两个队列,一个队列记录情况a-记为a队列,一个队列记录情况b-记为b队列
* 使用一个二维数组记录当前打印的层,第一层代表从左往右打印,第二层代表从右往左打印
* 当a队列打印完后,在打印b队列,在打印a队列。如此往复
*
*/
class Solution {
public List<List<Integer>> printFromTopToBottom(TreeNode root) {
List<List<Integer>> printList = new ArrayList();
if(root == null) {
return printList;
}
List<Integer> elementList = new ArrayList();
List<Stack<TreeNode>> stackList = new ArrayList(2);
Stack<TreeNode> currentStack = new Stack();
Stack<TreeNode> nextStack = new Stack();
stackList.add(currentStack);
stackList.add(nextStack);
currentStack.push(root);
TreeNode node;
int current = 0;
int next = 1;
while(!stackList.get(current).empty() || !stackList.get(next).empty()) {
// 弹出当前栈的栈顶
node = stackList.get(current).pop();
elementList.add(node.val);
if(current == 0) { // 等于0,则表示当前层数为从右往左打印
// 在栈中,先压入左节点,在压入右节点,打印时会先打印右节点在打印左节点
if(node.left != null) {
stackList.get(next).push(node.left); // 压入到下一层中,即get(next)
}
if(node.right != null) {
stackList.get(next).push(node.right);// 压入到下一层中,即get(next)
}
} else { // 否则相反
if(node.right != null) {
stackList.get(next).push(node.right);// 压入到下一层中,即get(next)
}
if(node.left != null) {
stackList.get(next).push(node.left); // 压入到下一层中,即get(next)
}
}
// stackList.get(current).empty() 的时候,代表当前层以及打印完成,重新初始化各个参数
if(stackList.get(current).empty()) {
current = 1 - current;
next = 1 - next;
printList.add(elementList);
elementList = new ArrayList();
}
}
return printList;
}
}