题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
if (pRoot == null) {
return res;
}
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(pRoot);
boolean isOdd = true;//奇数从左往右遍历
while (!queue.isEmpty()) {
int n = queue.size();
ArrayList<Integer> list = new ArrayList<>();
if (isOdd) {
//从左往右
for (int i = 0; i < n; i++) {
TreeNode cur = queue.poll();
list.add(cur.val);
if (cur.left != null) {
queue.add(cur.left);
}
if (cur.right != null) {
queue.add(cur.right);
}
}
isOdd = false;
} else {
//从右往左
for (int i = 0; i < n; i++) {
TreeNode cur = queue.pollLast();
list.add(cur.val);
if (cur.right != null) {
queue.addFirst(cur.right);
}
if (cur.left != null) {
queue.addFirst(cur.left);
}
}
isOdd = true;
}
res.add(list);
}
return res;
}
}
思路二: 正常层序遍历,奇数不变,偶数行反转,用reverse函数。