leetcode-95-树题-不同的二叉搜索树 发表于 2020-03-23 | 分类于 数据结构与算法 题目 解法12345678910111213141516171819202122232425262728293031323334353637383940/** * 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 {public: vector<TreeNode*> generateTrees(int n) { vector<TreeNode*> res; if(0 == n) return res; res = helper(1, n); return res; } vector<TreeNode*> helper(int start, int end){ vector<TreeNode*> res; if(start > end) res.push_back(NULL); for(int i = start; i <= end; ++i){ auto lefts = helper(start, i-1); auto rights = helper(i+1, end); for(auto l : lefts){ for(auto r : rights){ TreeNode *root = new TreeNode(i); root->left = l; root->right = r; res.push_back(root); } } } return res; }};