題:按照如圖方式遍歷二叉樹
個人思路:
1、用兩個棧實現,奇數層用第一個棧,偶數層放第二個棧
/**
* 層序遍歷數組,鋸齒形遍歷
* 第二層遍歷頂點
* 第二層按照右向左遍歷
* 第三層按照左向右遍歷
* 第四層按照右向左遍歷
* 依次。。。。
* Author : BlueSky 2019.11.15
* 4
* 2 6
* 1 3 5 7
* 輸出:4 6 2 1 3 5 7
*/
public class LayerTreeV2 {
public void foreachV1(TreeNode treeNode){
if(treeNode == null){
return;
}
List<List<Integer>> list = new ArrayList<List<Integer>>();
Stack<TreeNode> stackLeftFirst = new Stack<TreeNode>();
Stack<TreeNode> stackRightFirst = new Stack<TreeNode>();
stackLeftFirst.push(treeNode);
//int high = 2;
while (!stackLeftFirst.empty() || !stackRightFirst.empty()){
List<Integer> arrayList1 = new ArrayList();
while(!stackLeftFirst.empty()){
TreeNode node = stackLeftFirst.pop();
System.out.println(node.getVal());
arrayList1.add(node.getVal());
if(node.getLeft() != null){
stackRightFirst.push(node.getLeft());
}
if(node.getRight() != null){
stackRightFirst.push(node.getRight());
}
}
list.add(arrayList1);
List<Integer> arrayList2 = new ArrayList();
while(!stackRightFirst.empty()){
TreeNode node = stackRightFirst.pop();
System.out.println(node.getVal());
arrayList2.add(node.getVal());
if(node.getRight() != null){
stackLeftFirst.push(node.getRight());
}
if(node.getLeft() != null){
stackLeftFirst.push(node.getLeft());
}
}
list.add(arrayList2);
}
System.out.println(list.toString());
}
}
打印結果如圖: