leetcode 95: Unique Binary Search Trees II

本文介绍了一种通过递归方法生成所有可能的二叉搜索树(BST)的方法,并详细解释了如何保存这些BST。核心思想是在每一步递归中声明一个向量来存储左子树和右子树的所有组合。

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

Learned from http://blog.youkuaiyun.com/lanxu_yy/article/details/17504837. The hard thing about this problem is not how to generate a BST, but how to save the BST when one is generated. The idea here is to declare the vector in every recursion step and save all its left and right subtrees. Let's say I got m left subtrees and n right subtrees, I then generate m*n roots and push all these roots into the vector and return it.

/**
 * 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) {
        return helper(1,n);
    }
    vector<TreeNode*> helper(int start,int end)
    {
        vector<TreeNode*> subtree;
        if(start>end)
        {
            subtree.push_back(NULL);
            return subtree;
        }
        for(int i=start;i<=end;i++)
        {
            vector<TreeNode*> left=helper(start,i-1);
            vector<TreeNode*> right=helper(i+1,end);
            for(int j=0;j<left.size();j++)
                for(int k=0;k<right.size();k++)
                {
                    TreeNode* root=new TreeNode(i);
                    root->left=left[j];
                    root->right=right[k];
                    subtree.push_back(root);
                }
        }
        return subtree;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值