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

LEETCODE: Unique Binary Search Trees II

2014-12-28 19:34 381 查看
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


递归!

/**
* 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 left, int right) {
// The child of leaf is null.
if(left > right) return vector<TreeNode *>(1, nullptr);

// Get results, the rusults is the combination
// of all possible left sub tree and right sub tree.
vector<TreeNode *> results;
for(int ii = left; ii <= right; ii ++) {
// Get left sub trees and right sub trees.
vector<TreeNode *> lefts = generate(left, ii - 1);
vector<TreeNode *> rights = generate(ii + 1, right);
// Combinate them, add the current as root.
for(int jj = 0; jj < lefts.size(); jj ++) {
for(int kk = 0; kk < rights.size(); kk ++) {
TreeNode *newroot = new TreeNode(ii);
newroot->left = lefts[jj];
newroot->right = rights[kk];
results.push_back(newroot);
}
}
}
return results;
}
vector<TreeNode *> generateTrees(int n) {
return generate(1, n);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LEETCODE 算法 递归