Updated merge function to merge recursively