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

【LeetCode】Unique Binary Search Trees II

2014-08-16 16:42 337 查看
Given 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


confused what
"{1,#,2,3}"
means? >
read more on how binary tree is serialized on OJ.

OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:

1
/ \
2   3
/
4
\
5

The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.
思路:看程序就可以看到是将1到n遍历,然后选择其中的i,将位于其左边的和位于其右边的都遍历加入到vector中。
/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<TreeNode *> generate(int beg, int end)
{
vector<TreeNode *> ret;
if(beg>end){
ret.push_back(NULL);
return ret;
}
for(int i=beg;i<=end;i++){
vector<TreeNode *> TreeLeft = generate(beg, i-1);
vector<TreeNode *> TreeRight = generate(i+1, end);
for(int j=0;j<TreeLeft.size();j++){
for(int k=0;k<TreeRight.size();k++){
TreeNode* tmp = new TreeNode(i);
tmp->left = TreeLeft[j];
tmp->right = TreeRight[k];
ret.push_back(tmp);
}
}
}
return ret;
}

vector<TreeNode *> generateTrees(int n) {
return generate(1, n);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: