First of all,Both the left and right subtree of the binary search tree have their own binary search trees.This recursive definition determines that if I know all the binary search tree structures from 1 to n-1, the binary search tree with the knots of N can also be obtained.
The conversion relationship is as follows:
For a Binary Search Tree Containing N nodes, the root of the tree can start from I = 1 ~ N changes, and the numbers of left and right subtree nodes are I-1 and N-I, respectively.
After this analysis, the idea of dynamic planning is obvious. This is troublesome for copying a tree.
TreeNode *copyTree(TreeNode *root, int offSet){if (root == nullptr)return nullptr;TreeNode *nRoot = new TreeNode(root->val + offSet);nRoot->left = copyTree(root->left, offSet);nRoot->right = copyTree(root->right, offSet);return nRoot;} vector<TreeNode *> generateTrees(int n) {vector<TreeNode *> result;if (n == 0){result.push_back(nullptr);return result;}vector<vector<TreeNode*> > table(n + 1);TreeNode *t1 = new TreeNode(1);table[0] = {nullptr};table[1] = {t1};for (int i = 2; i < n + 1; i++){vector<TreeNode*> row;for (int j = 1; j < i + 1; j++){//vector<TreeNode*> lt = table[j - 1];//left: no offset//vector<TreeNode*> rt = table[i - j];//right: offset by jfor (auto lIt = table[j - 1].begin();lIt != table[j - 1].end(); lIt++){for (auto rIt = table[i - j].begin(); rIt != table[i - j].end(); rIt++){TreeNode *midNode = new TreeNode(j);midNode->left = copyTree(*lIt, 0);midNode->right = copyTree(*rIt, j);row.push_back(midNode);}}}table[i] = row;}return table[n]; }
Unique Binary Search Trees II