Java Queue solution


  • -1
    S
    public class Solution {
        
        public class Pair {
            int val , level;
            TreeNode node;
            public Pair(int val, int level, TreeNode node) {
                this.val = val;
                this.level = level;
                this.node = node;
            }
        }
        
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            
            if(root == null)
                return result;
            
            Queue<Pair> q = new LinkedList<Pair>();
            q.add(new Pair(root.val , 0 , root));
            
            while(!q.isEmpty()) {
                Pair p = q.poll();
                TreeNode node = p.node;
                
                if(result.size() < p.level + 1) {
                    List<Integer> list = new LinkedList<Integer>();
                    list.add(p.val);
                    result.add(list);
                } else {
                    List<Integer> list = result.get(p.level);
                    list.add(p.val);
                }
                
                if (node.left != null)
                    q.add(new Pair(node.left.val , p.level + 1, node.left));
                    
                if (node.right != null)
                    q.add(new Pair(node.right.val , p.level + 1, node.right));
            }
            
            return result;
        }
    }

Log in to reply
 

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