Java Divide and Conquer Solution (similar to merge sort) Easy to Understand


  • 0
    R
    public List<List<Integer>> findLeaves(TreeNode root) {
            if(root==null) return new ArrayList();
            List<Integer> cur = new ArrayList();
            cur.add(root.val);
            List<List<Integer>> l = findLeaves(root.left);
            List<List<Integer>> r = findLeaves(root.right);
            List<List<Integer>> result = merge(l,r);
            result.add(cur);
            return result;
        }
        
        public List<List<Integer>> merge(List<List<Integer>> l, List<List<Integer>> r){
            if(l.size()<r.size()) return merge(r,l);
            for(int i=0; i<r.size();i++){
                l.get(i).addAll(r.get(i));
            }
            return l;
        }

Log in to reply
 

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