Unique Binary Search Trees I & II

Unique Binary Search Trees

Given n, how many structurally unique BST's (binary search trees) that store values 1...n?

For example,
Given n = 3, there are a total of 5 unique BST's.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
题意:求1-n 这n个数可以构造多少棵BST树。

分析:数据结构中有一节树的计数问题,是可以有多少棵二叉树,与这个同理,基本原理如下图。树的个数 bn=b0*bn-1 + b1*bn-2 +...bn-1*b0(b0=1, b1=1)

也就是说,要求有多少棵树,在固定一个根节点之后,i个节点做左子树(构成一个左子树集合),n-i-1个节点做右子树(构成一个右子树集合),然后将集合中的树组合成一棵新的树。 该公式最终得到 bn=1/(n+1)(2n,n) 卡特兰数,问百度。


代码:

class Solution {
public:
    int numTrees(int n) {
        if(n==0 || n==1) return 1;
        int *b=new int[n+1]; //记录每个n对应有多少棵树
        memset(b,0,sizeof(int)*(n+1)); //注意初始化
        b[0]=1;b[1]=1;
        //int res=0;
        for(int i=2;i<=n;i++){
            for(int j=0;j<i;j++){
                b[i]+=(b[j]*b[i-j-1]);
            }
            
        }
        return b[n];
    }
};


Unique Binary Search Trees II

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
题意:题I是要求有多少棵BST树,

分析:II是要求出每棵树,思路借鉴I。用循环加递归的形式,代码较简单。

代码:

/**
 * 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 *> generateTrees(int n) {
        return gen(1,n);
    }
    
    vector<TreeNode *> gen(int left, int right){
        if(left>right){
             vector<TreeNode *> res;
             TreeNode *root=NULL;
             res.push_back(root);
             return res;
        }
        vector<TreeNode *> res;
        for(int i=left;i<=right;i++){//i表示根节点的val
            vector<TreeNode *> leftTreeSet=gen(left,i-1);//递归生成i的左子树集合
            vector<TreeNode *> rightTreeSet=gen(i+1,right);//生成i右子树集合
            
            for(int x=0;x<leftTreeSet.size();x++){ //左右子树集合中的 树两两组合
                for(int y=0;y<rightTreeSet.size();y++){
                    TreeNode *r= new TreeNode(i);
                    r->left=leftTreeSet[x];
                    r->right=rightTreeSet[y];
                    res.push_back(r);
                }
            }
            
        }
        return res;
    }
    
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值