安之字顺序打印二叉树:
题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class 安之字顺序打印二叉树 {
public static class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode node1 = new TreeNode(8);
TreeNode node2 = new TreeNode(6);
TreeNode node3 = new TreeNode(10);
TreeNode node4 = new TreeNode(5);
TreeNode node5 = new TreeNode(7);
TreeNode node6 = new TreeNode(9);
TreeNode node7 = new TreeNode(11);
node1.left=node2;
node1.right=node3;
node2.left=node4;
node2.right=node5;
node3.left=node6;
node3.right=node7;
ArrayList<ArrayList<Integer>> answer = Print(node1);
for (int i = 0; i < answer.size(); i++) {
ArrayList<Integer> temp = answer.get(i);
for (int j = 0; j < temp.size(); j++) {
System.out.print(temp.get(j)+" ");
}
System.out.println();
}
}
public static ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> answer = new ArrayList<>();
if (pRoot==null) {
return answer;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(pRoot);
int count = 1;
TreeNode node = null;
while (!queue.isEmpty()) {
ArrayList<Integer> row = new ArrayList<>();
ArrayList<TreeNode> noderow = new ArrayList<>();
while (!queue.isEmpty()) {
noderow.add(queue.poll());
}
for (int i = 0; i < noderow.size(); i++) {
node = noderow.get(i);
if (node.left!=null) {
queue.add(node.left);
}
if (node.right!=null) {
queue.add(node.right);
}
}
if (count%2==0) {
for (int i = noderow.size()-1; i >=0; i--) {
node = noderow.get(i);
row.add(node.val);
}
}else {
for (int i = 0; i < noderow.size(); i++) {
node = noderow.get(i);
row.add(node.val);
}
}
answer.add(row);
count++;
}
return answer;
}
}