Share my clean and easy java solution


  • 22
    S
        public class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
           List<List<Integer>> result = new ArrayList<List<Integer>>();
           
           if(root == null){
              return result;
           }
           
           Queue<TreeNode> queue = new LinkedList<TreeNode>();
           queue.offer(root);
           
           int curL = 0;
           while(!queue.isEmpty()){
               List<Integer> levelRs = new ArrayList<Integer>(); 
               curL = queue.size();
               for(int i=0;i<curL;i++){
                   TreeNode peek = queue.poll();
                   levelRs.add(peek.val);
                   if(peek.left!=null){
                       queue.offer(peek.left);
                   }
                   if(peek.right!=null){
                       queue.offer(peek.right);
                   }
               }
               result.add(levelRs);
           }
           
           return result;
        }  
    }

  • 0
    X

    it's so awesome~


  • 0
    X

    and u makes me like a idiot


  • 0
    X

    The two of us are crazy


Log in to reply
 

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