您的位置:首页 > 其它

Binary Tree Zigzag Level Order Traversal

2014-12-29 20:58 351 查看
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]
]

要求之字形输出节点值 即每隔行的输出顺序相反 很明显这与栈的定义相似 用栈来存储则每回输出的内容刚好与此前相反 若用一个栈则不能存储新的节点 所以 用两个栈 注意的是 从右向左输出时  添加节点的顺序也要改变为右向左  代码如下:

public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res=new ArrayList<List<Integer>>();
if(root==null) return res;
int count=0;
int level=1;
int num=1;
Stack<TreeNode> sta2=new Stack<TreeNode>();
sta2.push(root);
Stack<TreeNode> sta=new Stack<TreeNode>();
while(sta2.isEmpty()!=true||sta.isEmpty()!=true){
List<Integer> tmp=new ArrayList<Integer>();
num=level;
level=0;
if(count%2==0){
for(int i=0;i<num;i++){
tmp.add(sta2.peek().val);
if(sta2.peek().left!=null){
sta.add(sta2.peek().left);
level++;
}
if(sta2.peek().right!=null){
sta.add(sta2.peek().right);
level++;
}
sta2.pop();
}
}
if(count%2==1){
for(int i=0;i<num;i++){
tmp.add(sta.peek().val);
if(sta.peek().right!=null){
sta2.add(sta.peek().right);
level++;
}
if(sta.peek().left!=null){
sta2.add(sta.peek().left);
level++;
}
sta.pop();
}
}
res.add(tmp);
count++;
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  stack binary 遍历