给定一个整数 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
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<TreeNode*> generateTrees(int n) { 13 if(n == 0) 14 { 15 return vector<TreeNode*>{}; 16 } 17 return helper(1,n); 18 } 19 vector<TreeNode*> helper(int begin,int end) 20 { 21 vector<TreeNode*> res; 22 if(begin > end) 23 { 24 res.push_back(NULL); 25 return res; 26 } 27 for(int i = begin; i<= end;++i) 28 { 29 vector<TreeNode*> left = helper(begin,i-1); 30 vector<TreeNode*> right = helper(i+1,end); 31 for(auto l : left) 32 for(auto r: right) 33 { 34 TreeNode* root = new TreeNode(i); 35 root-> left = l; 36 root-> right = r; 37 res.push_back(root); 38 } 39 } 40 return res; 41 } 42 };
原文地址:https://www.cnblogs.com/Jawen/p/10816830.html
时间: 2024-10-09 02:09:30