Simple short java solution


  • 0
    J
       public List<List<Integer>> findLeaves(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if(root==null) return res;
        List<List<Integer>> left = findLeaves(root.left);
        List<List<Integer>> right = findLeaves(root.right);
        for(int i=0;i<Math.max(left.size(),right.size());i++){
            List<Integer> list = new ArrayList<>();
            List<Integer> ll = new ArrayList<>();
            List<Integer> rr = new ArrayList<>();
            if(i<left.size()) ll = left.get(i);
            if(i<right.size()) rr = right.get(i);
            list.addAll(ll);
            for(int j=0;j<rr.size();j++)
                list.add(rr.get(j));
                
            res.add(list);
        }
        List<Integer> t = new ArrayList<>();
        t.add(root.val);
        res.add(t);
        return res;
    }

Log in to reply
 

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