JAVA 3ms solution with annotation


  • 0
    H
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        //the index of cur list of int
        List<Integer> index = new ArrayList<Integer>();
        if(root!=null){
            //the index of cur list of TreeNode
            List<TreeNode> temp = new ArrayList<TreeNode>();
            temp.add(root);
            while(temp.size()>0){
                index = new ArrayList<Integer>();
                for(TreeNode one:temp){
                    index.add(one.val);
                }
                list.add(index);
                temp = nextLevelList(temp);
            }
        }
        
        return list;
    }
    
    //ltn : TreeNodes on the last level 
    //@todo: return TreeNodes in this level in order
    private List<TreeNode> nextLevelList(List<TreeNode> ltn){
        List<TreeNode> nextLevelTreeNodes = new ArrayList<TreeNode>();
        for(TreeNode one:ltn){
            if(one!=null){
                if(one.left!=null){
                    nextLevelTreeNodes.add(one.left); 
                }
                if(one.right!=null){
                    nextLevelTreeNodes.add(one.right); 
                }
            }
        }
        return nextLevelTreeNodes;
    }

  • 0
    H

    after seeing others solution
    I think this will be a little better XD

    public class Solution {
        
        private List<List<Integer>> result= new ArrayList<List<Integer>>();
        public List<List<Integer>> levelOrder(TreeNode root) {
            getAllResults(root,1);
            return result;
        }
        
       public void getAllResults(TreeNode node,int level){
           if(node!=null){
               if(result.size()<level){
                   result.add(new ArrayList<Integer>());
                   
               }
               result.get(level-1).add(node.val);
               if(node.left!=null){
                   getAllResults(node.left,level+1);
                   
               }
               if(node.right!=null){
                   getAllResults(node.right,level+1);
                   
               }
           }
       }
    }

Log in to reply
 

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