Simple Java Solution

  • 0

    All the leaf nodes are put in the list of index 0, their parents are put in 1, ... and root is in N. Thus for each node we can use recursion to get the index of its left and right child and the index + 1 will be the position for the current node.

    public class Solution {
        public List<List<Integer>> findLeaves(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();        
            proc(root, res);
            return res;
        private int proc(TreeNode node, List<List<Integer>> res) {
            if (node == null) return -1;
            int i = Math.max(proc(node.left, res), proc(node.right, res)) + 1;
            if (res.size() == i) res.add(new ArrayList<Integer>());
            return i;

Log in to reply

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