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.
Hide Tags
这个嘛,对于1 to n ,如果要用某个值做节点,那么这个值左部分的全部可能的树,递归调用获得,右部分同理,这样便可以获取结果。
#include <iostream> #include <vector> using namespace std; /** * 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 *> generateTrees(int n) { return help_f(1,n); } vector<TreeNode *> help_f(int l,int r) { vector<TreeNode *> ret; if(l>r){ ret.push_back(NULL); return ret; } for(int i=l;i<=r;i++){ vector<TreeNode *> lPart = help_f(l,i-1); vector<TreeNode *> rPart = help_f(i+1,r); for(int lidx=0;lidx<lPart.size();lidx++){ for(int ridx=0;ridx<rPart.size();ridx++){ TreeNode * pNode = new TreeNode(i); pNode->left = lPart[lidx]; pNode->right = rPart[ridx]; ret.push_back(pNode); } } } return ret; } }; int main() { return 0; }
时间: 2024-10-11 10:35:32