题目:请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
思路: 该问题为一个广度优先遍历问题,按题意所说,在遍历时要分奇数层和偶数层,利用队列数据结构来保存二叉树结点,通过对奇偶层的判断来决定元素是从列表的后面插入还是前面插入。
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class tree01 {
public static class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
// 二叉树的遍历,广度优先策略
// 思路:使用队列的数据结构
ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();
if (pRoot == null) {
return a;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(pRoot);
int i = 1;
while (!queue.isEmpty()) { //外层循环判断是否还有未遍历的结点
int count = queue.size();
ArrayList<Integer> tmp = new ArrayList<>();
while (count > 0) { //里层循环判断当前层是否还有未遍历完的结点
TreeNode node = queue.poll();
if (i % 2 == 0) {
tmp.add(0, node.val);
} else {
tmp.add(node.val);
}
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
count--;
}
a.add(tmp);
i++;
}
return a;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(5);
TreeNode node1_1 = new TreeNode(4);
TreeNode node1_2 = new TreeNode(7);
TreeNode node2_1 = new TreeNode(8);
TreeNode node2_2 = new TreeNode(9);
TreeNode node2_3 = new TreeNode(10);
root.left = node1_1;
root.right = node1_2;
node1_1.left = node2_1;
node1_1.right = node2_2;
node1_2.left = node2_3;
tree01 test = new tree01();
ArrayList<ArrayList<Integer>> print = test.Print(root);
System.out.println(print);
}
}
测试案例:
输出结果: