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;
}
}