[LeetCode]Unique Binary Search Trees

本文探讨了如何计算不同结构的二叉搜索树的数量,针对输入整数n,提供了求解1到n构造的不同二叉搜索树总数的方法。通过递归方式解决了n等于3时的特殊情况,并扩展至任意n值。

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

题目:

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

思路:

n=0,1,2时,可以直接给出答案。
当n>=3时,要考虑几种情况:3 插入 1,2 中,插入头部,插入尾部,插入中间。头和尾均有 numTrees(3-1)种结果,插入中间就要考虑 左右两侧数字的可能性。
扩展的n的情况,依旧头尾均有numTrees(n-1)种结果,插入中间i的位置,要考虑 1~i,i+1~n-1 左右两侧的可能,其结果为 numTrees(i)*numTrees(n-1-i)
用递归简单,而且明白。

代码:

public class Solution {
    public int numTrees(int n) {
        if(n==0) return 0;
        if(n==1) return 1;
        if(n==2) return 2;
        int sum=0;
        int i=n-2;
        while(i>0){
            sum=numTrees(n-1-i)*numTrees(i)+sum;
            i--;
        }
        sum=sum+2*numTrees(n-1);
        return sum;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值