Java: simple recursive solution, beats 87.36%


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

Log in to reply
 

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