Returns the number of Binary Search Trees for N.

Source: Internet
Author: User

GivenN, Generate all structurally uniqueBST's(Binary Search Trees) that store values 1...N.

For example,
GivenN= 3, your program shocould return all 5 unique BST's shown below.

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

 

Confused what"{1,#,2,3}"Means? > Read more on how binary tree is serialized on OJ.

 

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {private:    vector<TreeNode *> generate(int l, int r)    {        vector<TreeNode *> ans;         if (l > r)        {            ans.push_back(NULL);        }        else        {            for (int i=l; i<=r; i++){                vector<TreeNode *> left = generate(l, i-1);                vector<TreeNode *> right = generate(i+1, r);                for (int j=0; j<left.size(); j++)                {                   for (int k=0; k<right.size(); k++)                    {                        TreeNode *pRoot = new TreeNode(i);                        pRoot->left = left[j];                        pRoot->right = right[k];                        ans.push_back(pRoot);                    }                }            }                    }                return ans;    }public:    vector<TreeNode *> generateTrees(int n) {        return generate(1, n);    }};

 

Returns the number of Binary Search Trees for N.

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.