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] ]
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
LinkedList<TreeNode> stack=new LinkedList<TreeNode>();
LinkedList<TreeNode> curr=new LinkedList<TreeNode>();
List<List<Integer>> res=new ArrayList< List<Integer> >();
if(root==null) return res;
stack.add(root);
int flag=0;
while(!stack.isEmpty()){
curr=stack;
stack=new LinkedList<TreeNode>();
List<Integer> a=new LinkedList<Integer>();
while(curr.size()>0){
if(flag==1){
TreeNode tmpNode=null;
tmpNode=curr.peekLast();
if(tmpNode.right!=null) stack.addFirst(tmpNode.right);
if(tmpNode.left!=null) stack.addFirst(tmpNode.left);
a.add(tmpNode.val);
//System.out.print("flag="+flag+" val="+tmpNode.val+" ");
curr.pollLast();
}
else if(flag==0){
TreeNode tmpNode=null;
tmpNode=curr.peekFirst();
if(tmpNode.left!=null) stack.addLast(tmpNode.left);
if(tmpNode.right!=null) stack.addLast(tmpNode.right);
//System.out.print("flag="+flag+" val="+tmpNode.val+" ");
a.add(tmpNode.val);
curr.pollFirst();
}
}
//System.out.println();
res.add(a);
flag=1-flag;
}
return res;
}
}
本文介绍了一种算法,用于实现二叉树节点值的锯齿形层序遍历。从左到右再从右到左交替进行,并提供了一个具体的示例来展示如何实现这一遍历方式。
440

被折叠的 条评论
为什么被折叠?



