LeetCode--unique-binary-search-trees-ii

本文介绍了一种使用递归方法生成所有可能的唯一二叉搜索树(BST)的算法。通过选择不同节点作为根节点,并递归地构建左右子树,最终生成所有结构上唯一的BST组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述


Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

For example,
Given n = 3, your program should return all 5 unique BST's shown below.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3


confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.


OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / \
 2   3
    /
   4
    \
     5
The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    //递归创建
    vector<TreeNode *> creatTrees(int left,int right){
        vector<TreeNode *> res;
        if(left>right){
            res.push_back(NULL);
            return res;
        }
        for(int i=left;i<=right;i++){ //以i为根节点的树,其左子树由[1, i-1]构成, 其右子树由[i+1, n]构成。该原则建树具有唯一性
            vector<TreeNode *> left_res = creatTrees(left,i-1);
            vector<TreeNode *> right_res = creatTrees(i+1,right);
            //每个左边的子树跟所有右边的子树匹配,而每个右边的子树也要跟所有的左边子树匹配,总共有左右子树数量的乘积种情况
            int lsize = left_res.size();
            int rsize = right_res.size();
            for(int j=0;j<lsize;j++){
                for(int k=0;k<rsize;k++){
                    TreeNode *root = new TreeNode(i);
                    root->left = left_res[j];
                    root->right = right_res[k];
                    res.push_back(root);
                }
            }
        }
        return res;
    }
    vector<TreeNode *> generateTrees(int n) {
        //本题主要考察二叉排序树的构建
        //unique-binary-search-trees-i,我们可以知道结果的数目是一个卡特兰数列,当本题需要把所有可能的二叉排序
        //给构建出来要求解所有的树,自然是不能多项式时间内完成的思路是每次一次选取一个结点为根,然后递归求解左右子树的所有结果,最后根据左右子树的返回的所有子树,依次选取
        //然后接上(每个左边的子树跟所有右边的子树匹配,而每个右边的子树也要跟所有的左边子树匹配,总共有左右子树数量的乘积种情况),构造好之后作为当前树的
        //结果返回
        return creatTrees(1,n);  //从1作为root开始,到n作为root结束
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值