Very simple Java solution


  • 0
    V
    /**
     * 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>> levelOrder(TreeNode root) {
            if(root == null) return new ArrayList<List<Integer>>(); 
            
            Queue<TreeNode> q1 = new LinkedList<TreeNode>();
            Queue<TreeNode> q2 = new LinkedList<TreeNode>();
            
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            List<Integer> values = new ArrayList<Integer>();
            
            q1.add(root);
            
            while(!q1.isEmpty()) {
                TreeNode node = q1.poll();
                
                if(node.left != null)
                    q2.add(node.left);
                if(node.right != null)
                    q2.add(node.right);
                    
                values.add(node.val);
                
                if(q1.isEmpty()) {
                    q1 = q2;
                    result.add(values);
                    values = new ArrayList<Integer>();
                    q2 = new LinkedList<TreeNode>();
                }
            }
            
            return result;
        }
    }
    

Log in to reply
 

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