3ms Java Solution


  • 0
    P
    /**
     * 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) {
           List<List<Integer>> result = new LinkedList<List<Integer>>();
            List<TreeNode>queue = new ArrayList<TreeNode>();
            if(root==null)return result;
            int temp=1;
            List<Integer> list = new LinkedList<Integer>();
            list.add(root.val);
            queue.add(root.left);queue.add(root.right);
            result.add(list);
            while(queue.size()>0){
                List<Integer> list2 = new LinkedList<Integer>();
                int j = queue.size(); 
                     for(int i = j-1;i>=0;i--){
                    	if(queue.size()==0)break;
                        TreeNode node = queue.get(i);queue.remove(i);
                        if(node!=null){
                          list2.add(node.val);
                          if(temp==0){
                             queue.add(node.left);
                             queue.add(node.right);
                          }else{
                              queue.add(node.right);
                              queue.add(node.left);
                          }
                       }
                    }
                    if(temp==0)temp = 1;
                    else temp = 0;
                   
                
                if(list2.size()!=0)result.add(list2);
            }
          return result;  
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.