95. Unique Binary Search Trees II

Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.

Example:

Input: 3
Output:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

選定一個root之後用DFS helper function得到left/right subtrees,然後分別loop所有可能的left/right subtrees組合,把該root加到TreeNode* vector裡。

vector<TreeNode*> helper(int start, int end) {
    vector<TreeNode*> res;
    if (start > end) {
        res.push_back(nullptr);
        return res;
    }
    for (int i = start; i <= end; ++i) {
        auto lefts = helper(start, i - 1), rights = helper(i + 1, end);
        for (auto left : lefts) {
            for (auto right : rights) {
                TreeNode* root = new TreeNode(i);
                root->left = left;
                root->right = right;
                res.push_back(root);
            } 
        }
    }
    return res;
}
vector<TreeNode*> generateTrees(int n) {
    if (n == 0) return {};
    return helper(1, n);
}

Last updated

Was this helpful?