Java Solution. [2ms - 33 testcases]


  • 0
    T
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            
            if(root == null) {
                List<List<Integer>> emptyList = new ArrayList<List<Integer>>();
                return emptyList;
            }
            
            List<TreeNode> current = new ArrayList<TreeNode>();
            current.add(root);
            
            List<Integer> nodeValue = new ArrayList<Integer>();
            nodeValue.add(root.val);
            
            List<List<Integer>>allLists = new ArrayList<List<Integer>>();
            allLists.add(nodeValue);
            boolean direction = false;
            
            addNewList(allLists, current, direction);
            
            return allLists;
            
        }
        
        public void addNewList(List<List<Integer>>allLists, List<TreeNode>current, boolean direction) {
            
            List<Integer>values = new ArrayList<Integer>();
            List<TreeNode>nodes = new ArrayList<TreeNode>();
            if(direction == false) {
                for(int index = current.size() - 1; index >= 0; index--) {
                    if(current.get(index).right != null){
                        values.add(current.get(index).right.val);
                        nodes.add(current.get(index).right);
                    }
                    if(current.get(index).left != null){
                        values.add(current.get(index).left.val);
                        nodes.add(current.get(index).left);
                    }
                    
                }
            }else if(direction == true) {
                for(int index = current.size() - 1; index >= 0; index--) {
                    if(current.get(index).left != null){
                        values.add(current.get(index).left.val);
                        nodes.add(current.get(index).left);
                    }
                    if(current.get(index).right != null){
                        values.add(current.get(index).right.val);
                        nodes.add(current.get(index).right);
                    }
                }
            }
            
            if(nodes.size() == 0){
                return;
            }
            direction = !direction;
            allLists.add(values);
            addNewList(allLists, nodes, direction);
            
        }
    }
    

Log in to reply
 

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