LeetCode:95 不同的搜索二叉树 递归解法
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-binary-search-trees-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
- 因为是从1~n所有数字组成的二叉搜索树,我们自然想到,树的根有1,2,…n 种选择
- 选择根
x
的话,集合[1~x-1]
都在x
的左边,集合[x+1~n]
都在x
的右边,恰好地满足二叉搜索树的性质 - 只要找到所有以集合
[1~x-1]
和集合[x+1~n]
生成的搜索子树的集合trees_left, trees_right
,再将分别将他们之中的树与根x
拼接,就可以得到以x为根的所有二叉搜索树 - 令x遍历1~n,每次选择x不同,都可以得到不同的搜索子树集合
trees_left, trees_right
,拼接后加入结果即可
代码
/**
* 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:
/*
param l