給定一個整數 n,生成全部由 1 ... n 爲節點所組成的 二叉搜索樹 。ios
輸入:3 輸出: [ [1,null,3,2], [3,2,null,1], [3,1,null,null,2], [2,1,3], [1,null,2,null,3] ] 解釋: 以上的輸出對應如下 5 種不一樣結構的二叉搜索樹: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
蔥丁:spa
#include <iostream> #include <vector> using namespace std; struct TreeNode{ int val; TreeNode* left; TreeNode* right; TreeNode(int v):val(v),left(NULL),right(NULL){} }; class Solution { public: vector<TreeNode*> generateTrees(int n) { vector<TreeNode*> ret; if(n == 0) return ret; ret = reverse(1, n); return ret; } vector<TreeNode*> reverse(int start, int end){ vector<TreeNode*> ret; if(start>end){ ret.push_back(NULL); } cout<<"11"<<endl; for(int i=start; i<=end; i++){ vector<TreeNode*> left = reverse(start, i-1); cout<<"~~~"; vector<TreeNode*> right = reverse(i+1, end); cout<<"---"; for(auto l : left){ for(auto r : right){ TreeNode* root = new TreeNode(i); root->left = l; root->right = r; ret.push_back(root); } } } return ret; } void print(vector<TreeNode*> root){ TreeNode *tmp; for(int i=0; i<root.size(); i++){ tmp = root[i]; } } }; int main(){ Solution s; vector<TreeNode*> res = s.generateTrees(2); cout<<res.size()<<endl; cout<<res[0]->val<<" "<<res[0]->left<<" "<<res[0]->right->val<<endl; return 0; }