Java simple solution with postorder traversal


  • 0
    Y
    public class Solution {
    public List<List<Integer>> findLeaves(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        traversal(res, root);
        return res;
    }
    
    private int traversal(List<List<Integer>> res, TreeNode node) {
        if (node == null) {
            return 0;
        }
        int levelLeft = traversal(res, node.left);
        int levelRight = traversal(res, node.right);
        int level = Math.max(levelLeft, levelRight);
        if (res.size() < level + 1) {
            res.add(new ArrayList<>());
        }
        res.get(level).add(node.val);
        return level + 1;
    }
    

    }


Log in to reply
 

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