Unique Binary Search Trees II

来源:互联网 发布:雷电法术升级数据 编辑:程序博客网 时间:2024/06/05 18:48

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

For example,
Given n = 3, your program should return all 5 unique BST's shown below.

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

Subscribe to see which companies asked this question

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<TreeNode*> help(int start,int end)    {        vector<TreeNode*> ans;        if(start>end)        {            ans.push_back(NULL);        }        for(int i=start;i<=end;++i)        {            vector<TreeNode*> left = help(start,i-1);            vector<TreeNode*> right=help(i+1,end);            for(auto l:left)            for(auto r:right)            {                TreeNode* root = new TreeNode(i);                root->left = l;                root->right = r;                ans.push_back(root);            }        }         return ans;            }    vector<TreeNode*> generateTrees(int n) {        vector<TreeNode*> ans;        if(n<0) return ans;        for(int i=1;i<=n;++i)        {            vector<TreeNode*> left = help(1,i-1);            vector<TreeNode*> right=help(i+1,n);            for(auto l:left)            for(auto r:right)            {                TreeNode* root = new TreeNode(i);                root->left = l;                root->right = r;                ans.push_back(root);            }        }         return ans;    }};

0 0