Recursive solution Java


  • 0
    R
    class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ls = new ArrayList();
        traverse(ls,root,0);
        return ls;
        
    }
    
    public void traverse(List<List<Integer>> list, TreeNode node, int level) {
        if(node == null ) {
            return;
        }
        if(list.size() <= level) {
            list.add(new ArrayList());
        }
        list.get(level).add(node.val);
        int leveltemp = level + 1;
        traverse(list,node.left,leveltemp);
        traverse(list,node.right,leveltemp);
        
    }
    }

Log in to reply
 

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