@SuppressWarnings("unused")
public class ZigzagLevelTraversal {
static class TreeNode{
Integer val;
TreeNode left;
TreeNode right;
public TreeNode() {
}
public TreeNode(Integer val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
public Integer getVal() {
return val;
}
public void setVal(Integer val) {
this.val = val;
}
public TreeNode getLeft() {
return left;
}
public void setLeft(TreeNode left) {
this.left = left;
}
public TreeNode getRight() {
return right;
}
public void setRight(TreeNode right) {
this.right = right;
}
}
public static TreeNode preCreate(TreeNode treeNode){
Scanner scanner = new Scanner(System.in);
System.out.println("输入节点的值:");
int val = scanner.nextInt();
if (val!=0){
treeNode = new TreeNode();
treeNode.setVal(val);
treeNode.setLeft(preCreate(treeNode.getLeft()));
treeNode.setRight(preCreate(treeNode.getRight()));
}else{
treeNode = null;
}
return treeNode;
}
public static void visit(TreeNode btnode){
if(btnode!=null)
System.out.print(btnode.getVal() + " ,");
}
public static void preorder(TreeNode btnode) {
if(btnode!=null){
visit(btnode);
preorder(btnode.getLeft());
preorder(btnode.getRight());
}
}
public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if (root != null) {
queue.offer(root);
}
List<Integer> list ;
while (!queue.isEmpty()) {
int size = queue.size();
list = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
list.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
if (res.size() % 2 == 1) {
Collections.reverse(list);
}
res.add(list);
}
return res;
}
public static void main(String[] args) {
TreeNode treeNode = new TreeNode();
treeNode = preCreate(treeNode);
preorder(treeNode);
System.out.println(zigzagLevelOrder(treeNode));
}
}