[leedcode 103] 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]
]
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        //和正常的层序遍历的唯一不同是,增加一个标志flag,代表从左还是从右开始遍历,使用了Collections的静态方法reverse反转链表
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        List<Integer> seq=new ArrayList<Integer>();
        if(root==null) return res;
        LinkedList<TreeNode> queue=new LinkedList<TreeNode>();
        queue.add(root);
        int cutcont=1;
        int nextcont=0;
        boolean flag=false;
        while(!queue.isEmpty()){
              TreeNode node=queue.remove();
             seq.add(node.val);
             cutcont--;
            if(node.left!=null){
                queue.add(node.left);
                nextcont++;
            }
            if(node.right!=null){
                queue.add(node.right);
                nextcont++;
            }
         /*   while(cutcont>0){
                TreeNode node=queue.remove();
                seq.add(node.val);
                 cutcont--;
                if(node.left!=null){
                queue.add(node.left);
                nextcont++;
                }
                if(node.right!=null){
                queue.add(node.right);
                nextcont++;
            }
            }*/
            
            if(cutcont==0){
                if(flag){
                    Collections.reverse(seq);
                    
                }
                flag=!flag;
                res.add(seq);
                cutcont=nextcont;
                nextcont=0;
                seq=new ArrayList<Integer>();
                
            }
        }
        return res;
        
        
    }
    
}

 

你可能感兴趣的:(binary)