Simple BFS Java solution


  • 0
    L
    public List<List<Integer>> levelOrder(TreeNode root) {
    
        ArrayList<List<Integer>> l=new ArrayList<List<Integer>>();
    
        addLevel(l,0,root);
    
        return l;
    
    }
    
    private void addLevel(List<List<Integer>> l, int level, TreeNode root){
    
        if(root==null) return;
    
        if(l.size()==level) l.add(new ArrayList<Integer>());
    
        l.get(level).add(root.val);
    
        addLevel(l,level+1,root.left);
    
        addLevel(l,level+1,root.right);
    }

  • 7
    C

    I think this solution should be DFS instead of BFS


Log in to reply
 

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