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,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
解题思路:
题意:按层次遍历二叉树,开始从左到右遍历,下一层从右到左遍历,然后又从左到右遍历,每层遍历完下一层遍历方向相反。
思路: 首先层次遍历很容易想到使用队列,记录遍历的层次,凡是奇数层将队列中节点的值按顺序添加到链表中,若是偶数层则将队列逆序后添加到链表中。
然后逆序输出想到了栈。
最后使用两个栈来遍历该二叉树,一个栈存储当前层次的节点,每pop一个节点,将节点值添加到list中,然后判断该节点是否有孩子节点,若有则将它们压入另外一个栈中。每次循环输出的栈中节点即为树的一层节点。
注意: 左右孩子节点压入的顺序,需要从左到右输出的层次节点在入栈的时候先压入右孩子。
public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result=new ArrayList<List<Integer>>();
Stack<TreeNode> stack1=new Stack<TreeNode>();
Stack<TreeNode> stack2=new Stack<TreeNode>();
TreeNode node=root;
if(root==null){
return result;
}
stack1.push(root);
while(!stack1.isEmpty()||!stack2.isEmpty()){
List<Integer> data=new ArrayList<Integer>();
if(!stack1.isEmpty()){
while(!stack1.isEmpty()){
node=stack1.pop();
data.add(node.val);
if(node.left!=null){
stack2.push(node.left);
}
if(node.right!=null){
stack2.push(node.right);
}
}
result.add(data);
}else if(!stack2.isEmpty()){
while(!stack2.isEmpty()){
node=stack2.pop();
data.add(node.val);
if(node.right!=null){
stack1.push(node.right);
}
if(node.left!=null){
stack1.push(node.left);
}
}
result.add(data);
}
}
return result;
}
}