标签:struct for 结构 main name nbsp ace == tor
给定一个整数 n,生成所有由 1 ... n 为节点所组成的 二叉搜索树 。
输入: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
葱丁:
#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; }
标签:struct for 结构 main name nbsp ace == tor
原文地址:https://www.cnblogs.com/bailuoxi/p/13199268.html