Skip to content
Problem 894 · LeetCode 894(opens in a new tab)

All Possible Full Binary Trees

MediumDynamic programming

A binary tree is full when every node has either no children or exactly two. Given a whole number n, build every full binary tree that has exactly n nodes, with every node holding the value 0.

Return a list with the root of each such tree. The trees may come back in any order. If no full tree has n nodes, return an empty list.

Example 1

Input:  n = 5
Output: [[0,0,0,0,0],              (3-node part on the left)
         [0,0,0,null,null,0,0]]   (3-node part on the right)
Why:    below the root, 4 nodes split as 3 + 1 or 1 + 3
2 more examples and the constraints

Example 2

Input:  n = 1
Output: [[0]]
Why:    a single leaf is a full tree

Example 3

Input:  n = 4
Output: []
Why:    a full tree always has an odd number of nodes

Constraints

  • 1 ≤ n ≤ 20
  • Every node's value is 0

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Plain recursionO(2ⁿ)
  2. Recursion with memoO(2ⁿ)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 19Verdict
Plain recursionO(2ⁿ)
Passes; rebuilds sizes
Recursion with memoO(2ⁿ)
Best; each size once

n = the number of nodes. The trees themselves number about 2ⁿ / n^1.5.

Edge cases to test

  • Even n. No full tree has an even number of nodes; return [].
  • n = 1. The answer is one tree: a single leaf.
  • n = 3. Exactly one tree: a root with two leaves.
  • Largest n. n = 19 has 4,862 trees; n = 20 is even, so it has none.

Common mistakes

  • Trying even sizes for a subtree, which can never be full and only wastes calls.
  • In plain recursion, calling for the right subtrees inside the loop over left trees, which rebuilds them once per left tree.
  • Forgetting the even-n case and recursing into sizes like 0.

How to talk through it

  1. 1Clarify. Can the trees share nodes? Does the order of the list matter? What should an even n return?
  2. 2State the structure. A full tree is a root over two full subtrees with odd sizes adding up to n − 1.
  3. 3Write the recursion. Loop over odd left sizes and pair every left tree with every right tree.
  4. 4Add the memo. Store the list for each size so it is built once and shared.
  5. 5Test out loud. Run n = 1, n = 4 and n = 5, and check the count matches 1, 0 and 2.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?