思路一:层序遍历的变式,辅助一个栈
从左到右采用层序遍历的思路,从右到左辅助一个栈。
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
// 之字形打印
if (root == null) {
return new LinkedList<>();
}
// 这个树不是空的
Queue<TreeNode> queue = new LinkedList<>();
boolean flag = true;//如果是true就从左到右,反之从右到左
queue.add(root);
List<List<Integer>> res = new LinkedList<>();
while (!queue.isEmpty()) {
int count = queue.size();
List<Integer> list = new LinkedList<>();
if (flag) {//应该从左到右打印
for (int i = 0; i < count; i++) {
TreeNode tmp = queue.remove();
list.add(tmp.val);
if (tmp.left != null) queue.add(tmp.left);
if (tmp.right != null) queue.add(tmp.right);
}
} else {//应该从右到左打印
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < count; i++) {
TreeNode tmp = queue.remove();
stack.push(tmp.val);
if (tmp.left != null) queue.add(tmp.left);
if (tmp.right != null) queue.add(tmp.right);
}
while (!stack.isEmpty()) {
list.add(stack.pop());
}
}
res.add(list);
flag = !flag;
}
return res;
}
}
思路二:采用两个栈,比较巧妙。
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
stack1.push(root);
int count = 1;
while (!stack1.isEmpty() || !stack2.isEmpty()) {
ArrayList<Integer> list = new ArrayList<>();
if (count % 2 == 1) {//取出来,先存左儿子,再存右儿子
while (!stack1.isEmpty()) {
TreeNode tmp = stack1.pop();
list.add(tmp.val);
if (tmp.left != null) stack2.push(tmp.left);
if (tmp.right != null) stack2.push(tmp.right);
}
} else {//取出来,先存右儿子,再存左儿子
while (!stack2.isEmpty()) {
TreeNode tmp = stack2.pop();
list.add(tmp.val);
if (tmp.right != null) stack1.push(tmp.right);
if (tmp.left != null) stack1.push(tmp.left);
}
}
count++;
res.add(list);
}
return res;
}
}