版权声明:本文为博主原创文章,未经博主许可允许转载。 https://blog.csdn.net/qq_29600137/article/details/89253822
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
Example:
Input: 3 Output: [ [1,null,3,2], [3,2,null,1], [3,1,null,null,2], [2,1,3], [1,null,2,null,3] ] Explanation: The above output corresponds to the 5 unique BST's shown below: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
题目大意:
输入n,使得1-n可以构成一个二叉树,该二叉树满足 左节点<父节点<右节点。
解题思路:
搜索从(1,n)开始。每次的接收为(start,end)这个区间,遍历这个区间,使得这个区间内每个节点都当一次父节点,依次返回构成树的root节点。
/**
* 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 {
private:
vector<TreeNode*> dfs(int start, int end){
vector<TreeNode*> tmp;
if(start>end){
tmp.push_back(NULL);
return tmp;
}
for(int i = start; i<=end;i++){
vector<TreeNode*> l = dfs(start, i-1);
vector<TreeNode*> r = dfs(i+1, end);
for(int j = 0; j<l.size();j++){
for(int k = 0;k<r.size();k++){
TreeNode *root = new TreeNode(i);
root->left = l[j];
root->right = r[k];
tmp.push_back(root);
}
}
}
return tmp;
}
public:
vector<TreeNode*> generateTrees(int n) {
if(n==0) return vector<TreeNode*>(0);
return dfs(1,n);
}
};