Share my accepted java solution


  • 0
    M
    1. 2ms

       public List<List<Integer>> levelOrderBottom(TreeNode root) {
      
          List<List<Integer>> ret = new ArrayList<List<Integer>>();
          helper(ret , root,0);  
          return ret;
         }
       private void helper(List<List<Integer>> ret, TreeNode root, int level){
       if(root==null) return;
       
       List<Integer> row;
       if(ret.size()<=level){
           row = new ArrayList<>();
           row.add(root.val);
           ret.add(0,row);
       }else{
           row = ret.get(ret.size()-1-level);
           row.add(root.val);
       }
       
       helper(ret, root.left,level+1);
       helper(ret, root.right, level+1);
      

      }

    2. 3ms

       TreeNode prev = null;
       TreeNode rightmost = null;
      
       public List<List<Integer>> levelOrderBottom(TreeNode root) {
       List<List<Integer>> ret = new ArrayList<>();
       List<Integer> subret = new ArrayList<>();
       if(root == null) return ret;
       
       rightmost = root; prev = root;
       Queue<TreeNode> que = new LinkedList<TreeNode>();
       que.add(root);
       
       while(!que.isEmpty()){
           TreeNode curr = que.poll();
           subret.add(curr.val);
      
           if(curr.left!=null||curr.right!=null) prev = curr;
           if(curr.left!=null) que.add(curr.left);
           if(curr.right!=null) que.add(curr.right);
           if(curr == rightmost){
               ret.add(0,subret);
               subret = new ArrayList<>();
               if(curr.left!=null || curr.right!=null){
                   rightmost = curr.right==null?curr.left:curr.right;
               }else{
                   rightmost = prev.right==null?prev.left:prev.right;
               }
           }            
       }
       return ret;
      

      }

    1. 4ms

       public List<List<Integer>> levelOrderBottom(TreeNode root) {
       List<List<Integer>> ret = new ArrayList<List<Integer>>();
       if(root==null) return ret;
       
       Queue<TreeNode> que = new LinkedList<>();
       que.add(root);
       while(!que.isEmpty()){
           que = helper(ret ,  que);
       }
       
       return ret;
       } private Queue<TreeNode> helper(List<List<Integer>> ret, Queue<TreeNode> que){
       Queue<TreeNode> newq = new LinkedList<>();
       List<Integer> sub = new ArrayList<>();
       while(!que.isEmpty()){
           TreeNode temp = que.poll();
           sub.add(temp.val);
           
           if(temp.left!=null) newq.add(temp.left);
           if(temp.right!=null) newq.add(temp.right);
       }
       ret.add(0,sub);
       return newq;
      

      }


Log in to reply
 

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