描述
给定一个二叉树,返回该二叉树的之字形层序遍历,(第一层从左向右,下一层从右向左,一直这样交替)
例如:
给定的二叉树是{1,2,3,#,#,4,5}
该二叉树之字形层序遍历的结果是
[
[1],
[3,2],
[4,5]
]
思路:
之字形输出,bfs层次遍历,可以用队列也可以用栈,
如果用队列,需要设定变量,基数层从左往右输出,偶数层从右往左输出(塞入result的时候翻转)
如果用栈,可以使用两个栈,这样的话就不用翻转了
代码:栈
import java.util.ArrayList;
import java.util.Stack;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > result = new ArrayList<>();
if (pRoot == null) {
return result;
}
//基数层从左往右输出,偶数层从右往左输出
//基数层 从右往左存 栈 先入后出
Stack<TreeNode> stack1 = new Stack<>();
//偶数层 从左往右存 这样就可以先输出右边
Stack<TreeNode> stack2 = new Stack<>();
stack1.add(pRoot);
while(!stack1.isEmpty() || !stack2.isEmpty()) {
ArrayList<Integer> temp = new ArrayList<>();
if (!stack1.isEmpty()) {
while(!stack1.isEmpty()) {
TreeNode node = stack1.pop();
temp.add(node.val);
if (node.left != null) {
stack2.add(node.left);
}
if (node.right != null) {
stack2.add(node.right);
}
}
result.add(temp);
continue;
}
if (!stack2.isEmpty()) {
while(!stack2.isEmpty()) {
TreeNode node = stack2.pop();
temp.add(node.val);
//必须先塞右孩子节点
if (node.right != null) {
stack1.add(node.right);
}
if (node.left != null) {
stack1.add(node.left);
}
}
result.add(temp);
continue;
}
}
return result;
}
}