LeetCode Top Interview Questions 103. Binary Tree Zigzag Level Order Traversal (Java版; Medium)
题目描述
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right,
then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
第一次做; 使用两个栈实现之字形打印; 不用统计个数和层数
/*
之字形打印二叉树, 使用两个栈就不用记录个数和层数了
*/
import java.util.List;
import java.util.ArrayList;
import java.util.Stack;
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(root==null)
return res;
ArrayList<Integer> tmp = new ArrayList<>();
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
stack1.push(root);
TreeNode cur;
while(!stack1.isEmpty() || !stack2.isEmpty()){
while(!stack1.isEmpty()){
cur = stack1.pop();
tmp.add(cur.val);
//左右
if(cur.left!=null)
stack2.push(cur.left);
if(cur.right!=null)
stack2.push(cur.right);
}
if(!tmp.isEmpty()){
res.add(new ArrayList<Integer>(tmp));
tmp.clear();
}
while(!stack2.isEmpty()){
cur = stack2.pop();
tmp.add(cur.val);
//右左
if(cur.right!=null)
stack1.push(cur.right);
if(cur.left!=null)
stack1.push(cur.left);
}
if(!tmp.isEmpty()){
res.add(new ArrayList<Integer>(tmp));
tmp.clear();
}
}
return res;
}
}