您的位置:首页 > 产品设计 > UI/UE

95. Unique Binary Search Trees II ,leetcode

2016-10-26 17:00 351 查看

题目:

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

代码:

/**
* 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:
TreeNode* copyAndaddValue(TreeNode* root, int val)
{
if(root == NULL)return root;
TreeNode* p = new TreeNode(root->val + val);
p->left = copyAndaddValue(root->left, val);
p->right = copyAndaddValue(root->right, val);
return p;
}
vector<TreeNode*> generateTrees(int n) {

if(n == 0)return vector<TreeNode*>();
vector<vector<TreeNode*>> dp(n+1);
dp[0] = vector<TreeNode*>{nullptr};

for(int i = 1; i < n + 1; i++)
for(int k = 1; k <= i; k++)
{
//TreeNode* r = new TreeNode(k);不能写在这里
for(auto p1 : dp[k - 1])
for(auto p2 : dp[i - k])
{
TreeNode* r = new TreeNode(k);
r->left = p1;
r->right = copyAndaddValue(p2, k);
dp[i].push_back(r);
}
}
return dp
;
}
};

总结:

这一题和95题思路一样都是用动态规划,用dp【i】保存结果,难点是,在k的右边在使用dp【i-k】的时候,需要每个节点的val加上k,即,需要多写一个
TreeNode* copyAndaddValue(TreeNode* root, int val)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: