A farmer buys a batch of trees, which he wishes to plant in a square grid. For example, if he had $25$ trees, then he could plant them as shown below.

[asy]
size(3cm,0);
dot((0,0));
dot((0,1));
dot((0,2));
dot((0,3));
dot((0,4));
dot((1,0));
dot((1,1));
dot((1,2));
dot((1,3));
dot((1,4));
dot((2,0));
dot((2,1));
dot((2,2));
dot((2,3));
dot((2,4));
dot((3,0));
dot((3,1));
dot((3,2));
dot((3,3));
dot((3,4));
dot((4,0));
dot((4,1));
dot((4,2));
dot((4,3));
dot((4,4));
[/asy]

However, the farmer finds that he cannot plant his trees in a square grid. If he had $20$ more trees, or if he had $39$ fewer trees, then he could plant his trees in a square grid. How many trees did the farmer buy?
1. Let \( x \) be the number of trees the farmer initially has. According to the problem, if the farmer had \( x + 20 \) trees, he could plant them in a square grid. This implies that \( x + 20 \) is a perfect square. Similarly, if the farmer had \( x - 39 \) trees, he could also plant them in a square grid, implying that \( x - 39 \) is a perfect square.

2. Let \( n^2 \) be the perfect square such that \( x + 20 = n^2 \). Similarly, let \( m^2 \) be the perfect square such that \( x - 39 = m^2 \).

3. We now have the equations:
   \[
   x + 20 = n^2
   \]
   \[
   x - 39 = m^2
   \]

4. Subtract the second equation from the first:
   \[
   (x + 20) - (x - 39) = n^2 - m^2
   \]
   \[
   59 = n^2 - m^2
   \]

5. Using the difference of squares formula, we get:
   \[
   n^2 - m^2 = (n + m)(n - m)
   \]
   Therefore:
   \[
   (n + m)(n - m) = 59
   \]

6. Since 59 is a prime number, the factors of 59 are 1 and 59. Thus, we have two equations:
   \[
   n + m = 59
   \]
   \[
   n - m = 1
   \]

7. Solve these two equations simultaneously. Add the two equations:
   \[
   (n + m) + (n - m) = 59 + 1
   \]
   \[
   2n = 60
   \]
   \[
   n = 30
   \]

8. Substitute \( n = 30 \) back into the equation \( n - m = 1 \):
   \[
   30 - m = 1
   \]
   \[
   m = 29
   \]

9. Now substitute \( n = 30 \) into the equation \( x + 20 = n^2 \):
   \[
   x + 20 = 30^2
   \]
   \[
   x + 20 = 900
   \]
   \[
   x = 880
   \]

10. Verify the solution by checking if \( x - 39 \) is a perfect square:
    \[
    x - 39 = 880 - 39 = 841
    \]
    \[
    841 = 29^2
    \]
    Since 841 is indeed a perfect square, our solution is verified.

The final answer is \(\boxed{880}\)