按层打印二叉树以及按之字形打印二叉树
定义树节点
public static class TreeNode {
int value;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.value = val;
}
}
按层打印
// 按层 用队列
public static void printByLayer(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
if (root == null) {
return;
}
queue.offer(root);
while (queue.size() != 0) {
TreeNode cur = queue.poll();
System.out.println(cur.value);
if (cur.left != null) {
queue.offer(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
}
}
}
按之字打印
public static ArrayList<ArrayList<Integer>> printLikeZhi(TreeNode root) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
// 用两个栈 接收奇数层和偶数层
Stack<TreeNode> s1 = new Stack<>(); // 奇数层
Stack<TreeNode> s2 = new Stack<>(); // 偶数层
ArrayList<Integer> list = new ArrayList<>();
if (root == null) {
return res;
}
s1.push(root);
while (!s1.isEmpty() || !s2.isEmpty()) {
while (!s1.isEmpty()) { // 奇数层不为空
TreeNode cur = s1.pop(); // 弹出s1
// System.out.println(cur.value);
list.add(cur.value);
if (cur.left != null) { // s2中 加入从s1弹出的孩子 先加左再加右
s2.push(cur.left);
}
if (cur.right != null) {
s2.push(cur.right);
}
}
if (list.size() > 0) {
res.add(new ArrayList<>(list));
list.clear();
}
while (!s2.isEmpty()) { // 偶数层不为空
TreeNode cur = s2.pop(); // 弹出s1
list.add(cur.value);
// System.out.println(cur.value);
if (cur.right != null) { // s1中 加入从s2弹出的孩子 先加右再加左
s1.push(cur.right);
}
if (cur.left != null) {
s1.push(cur.left);
}
}
if (list.size() > 0) {
res.add(new ArrayList<>(list));
list.clear();
}
}
return res;
}