Simple O(N) postorder (bottom - up) solution


  • 0
    public List<List<Integer>> findLeaves(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        dfs(root, result);
        
        return result;
    }
    
    int dfs(TreeNode node, List<List<Integer>> levels) {
        if (node == null) return -1;
    
        int depth = Math.max(
            dfs(node.left, levels),
            dfs(node.right, levels)) + 1;
        
        if (levels.size() == depth) {
            levels.add(new ArrayList<>());
        }
        
        levels.get(depth).add(node.val);
        
        return depth;
    }

Log in to reply
 

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