Unique Binary Search Trees II

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.