从物理学到计算机,再到硬件,再到人工智能!
蓝桥杯备赛 (LintCode上刷的第17题)
问题描述
给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行)
样例输出
JAVA代码实现
package tree;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class ZigzagLevelOrder1230 {
/**
* Z字型打印二叉树:先从左往右,下一层再从右往左,层与层之间交替进行
* @param root the root of the binary tree
* @return Z字型的数列
*/
public List<List<Integer>> zigzagLevelOrder(TreeNode1230 root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null) {
return result;
}
Stack<TreeNode1230> currLevel = new Stack<>();
Stack<TreeNode1230> nextLevel = new Stack<>();
Stack<TreeNode1230> tmp;
//当前这一层放进根节点
currLevel.push(root);
//记录遍历顺序
boolean normalOrder = true;
while (!currLevel.isEmpty()) {
ArrayList<Integer> currLevelResult = new ArrayList<>();
while (!currLevel.isEmpty()) {
TreeNode1230 node = currLevel.pop();
//添加根节点
currLevelResult.add(node.val);
//开始每一层遍历
if (normalOrder) {
if (node.left != null) {
nextLevel.push(node.left);
}
if (node.right != null) {
nextLevel.push(node.right);
}
} else {
if (node.right != null) {
nextLevel.push(node.right);
}
if (node.left != null) {
nextLevel.push(node.left);
}
}
}
result.add(currLevelResult);
//当前层下移
tmp = currLevel;
currLevel = nextLevel;
nextLevel = tmp;
//改变顺序
normalOrder = !normalOrder;
}
return result;
}
}