Beats around 44% of the Java Solutions


  • 0
    R
        public List<List<Integer>> levelOrder(TreeNode root) {
            
            if(root == null) {
                return new LinkedList<>();
            }
            
            List<List<Integer>> list = new LinkedList<>();
            List<Integer> l = new LinkedList<>();
            l.add(root.val);
            list.add(l);
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            List<List<Integer>> result = a(queue, list);
            // Collections.reverse(result);
            return result;
            
        }
        
        public List<List<Integer>> a(Queue<TreeNode> queue, List<List<Integer>> list) {
            
            if(queue.isEmpty()) {
                return list;
            }
            
            List<Integer> l = new LinkedList<>();
            Queue<TreeNode> q = new LinkedList<>();
            while (!queue.isEmpty()) {
                TreeNode node = queue.poll();
    
                if (node.left != null) {
                    q.add(node.left);
                    l.add(node.left.val);
                }
                if (node.right != null) {
                    q.add(node.right);
                    l.add(node.right.val);
                }
            }
            if(!l.isEmpty()) {
            list.add(l);            
            }
            return a(q, list);
        }
    

Log in to reply
 

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