[二叉搜索树][递归]leetcode95:不同的二叉搜索树Ⅱ(medium)

编程入门 行业动态 更新时间:2024-10-27 20:31:03

[二叉搜索树][<a href=https://www.elefans.com/category/jswz/34/1771140.html style=递归]leetcode95:不同的二叉搜索树Ⅱ(medium)"/>

[二叉搜索树][递归]leetcode95:不同的二叉搜索树Ⅱ(medium)

题目:

题解:

  • 分治法
  • 每次根据根节点i来划分左右子树,[1,i-1]为所有左子树的集合,[i,n]为所有右子树的集合,等到区间内没有元素时,分治法的最小子问题解决,那么左右子树的集合也得解了。

代码如下:

class Solution {
public:vector<TreeNode*> generateTrees(int n) {if(n==0)return {};return helper(1,n);}vector<TreeNode*> helper(int begin,int end){vector<TreeNode*> result;if(begin>end)//此时没有数字{result.push_back(nullptr);return result;}for(int i=begin;i<=end;++i){//i作为根节点,然后分为左子树的数字范围[begin,i-1],右子树的数字范围[i,end]//当区间内没有元素时,最小子问题解决,那么左右子树的集合也得解了vector<TreeNode*> left_trees=helper(begin,i-1);//得到左子树的集合vector<TreeNode*> right_trees=helper(i+1,end);//得到右子树的集合//左右子树两两组合for(auto l:left_trees){for(auto r:right_trees){TreeNode* root=new TreeNode(i);//数字i作为根节点root->left=l;root->right=r;result.push_back(root);}}}return result;}};

更多推荐

[二叉搜索树][递归]leetcode95:不同的二叉搜索树Ⅱ(medium)

本文发布于:2023-07-28 18:51:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1279615.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   medium

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!