Very Easy to Understand solution in Java-making best use of ArrayList


  • 0
    D

    To understand the solution, you have to know how array list works. See the snippet:

    public static void main(String[] args) {
       ArrayList<Integer> ls = new ArrayList<Integer>();
           ls.add(0, 5);
           ls.add(0, 6);
           for(int l:ls)
        	   System.out.println(l);
       
    }
    

    The output of the above code is : 6,5. That is the key idea of the below program.

    public class Solution {
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            
             List<List<Integer>> outer = new ArrayList<List<Integer>> ();
             List<Integer>  inner = new ArrayList<Integer> ();
    
      
             Queue<TreeNode> queue= new LinkedList<TreeNode>();
              TreeNode dummy=new TreeNode(0);
             
               if(root!=null) {
                  
                   queue.offer(root);
               
              queue.offer(dummy);
               }
              while(!queue.isEmpty()){
                   TreeNode temp=queue.poll();
                   if(temp!=dummy) inner.add(temp.val);
                   if(temp==dummy){
                            outer.add(0,inner);
                            
                       if(!queue.isEmpty())
                        queue.add(dummy);
                        
                         inner = new ArrayList<Integer> ();
                       }
                       
                      
                   
                   if(temp.left!=null)
                   queue.offer(temp.left);
                   if(temp.right!=null)
                   queue.offer(temp.right);
                       
                   
                   
                  
              }
           
              return outer;
              
              
        }
    }

Log in to reply
 

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