Binary Tree Zigzag Level Order Traversal

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;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章