题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推
import java.util.ArrayList;
import java.util.Stack;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
//当前是奇数层,就先保存左结点再保存右结点;
//当前是偶数层,就先保存右结点再保存左结点;
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
if (root == null) {
return new ArrayList<>();
}
List<List<Integer>> result = new ArrayList<>();
List<TreeNode> queueList = new ArrayList<>();
queueList.add(root);
int nextLevelNodeCount = 1;
boolean jishu = true;
while (!queueList.isEmpty()) {
List<Integer> saveNodeValueTempList = new ArrayList<>(nextLevelNodeCount);
int count = 0;
for (int i = 0; i < nextLevelNodeCount; i++) {
TreeNode node = queueList.remove(0);
saveNodeValueTempList.add(node.val);
// 都是从左到右放入
if (node.left != null) {
queueList.add(node.left);
count++;
}
if (node.right != null) {
queueList.add(node.right);
count++;
}
}
// 如果是偶数,需要反转
if (!jishu) {
saveNodeValueTempList = reverseQueueList(saveNodeValueTempList);
}
jishu = !jishu;
nextLevelNodeCount = count;
result.add(saveNodeValueTempList);
}
return result;
}
private List<Integer> reverseQueueList(List<Integer> queueList) {
List<Integer> result = new ArrayList<>();
for (int i = queueList.size() - 1; i >= 0; i--) {
result.add(queueList.get(i));
}
return result;
}
}