[leetCode] Unique Binary Search Trees

本文介绍如何计算和生成不同数量的唯一二叉搜索树。通过递归算法,解决给定数值n时所有独特二叉搜索树的数量及结构生成问题。

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

题目一:
Given n, how many structurally unique BSTs (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
思路:

建立count[]数组,存放从1到n每一个数对应的BST的个数。
对于数n,可能有多少个BST呢?这个是由它的根节点分布决定的,若根节点为root,左子树的个数就是count[root-1]的值,右子树的个数就是count[i-root]的值,两个解的乘积就是根节点为root,借点总数为i的所有BST的个数。将root从1到i遍历一遍,就得到了count[i],即i个结点的所有解。

实现代码如下:

public class Solution {
    public int numTrees(int n) {
        int[] count = new int[n+1];
        count[0] = 1;
        for (int i = 1; i <= n; i++) {
            for (int root = 1; root <= i; root++) {
                int left = count[root-1];
                int right = count[i-root];
                count[i] += left*right;
            }
        }
        return count[n];
    }
}
Unique Bin
题目二:
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
思路:

找到一个数作为根结点,剩余的数分别划入左子树或者右子树。

实现代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<TreeNode> generateTrees(int n) {
        if(n<1){
            return new ArrayList<TreeNode>();
        }
        return generateTrees(1,n);  
    }
    //函数功能:树节点中的value由start~end构成的二叉搜索树的所有结果
    private List<TreeNode> generateTrees(int start, int end) {
        List<TreeNode> res=new ArrayList<TreeNode>();
        if(end<start){
            res.add(null);
            return res;
        }
        for(int i=start;i<=end;i++){
            //产生以i为根节点,start~i-1构成左子树,i+1~end构成右子树
            List<TreeNode> leftSubTreeList=generateTrees(start,i-1);
            List<TreeNode> rightSubTreeList=generateTrees(i+1,end);
            //遍历并由根节点组合左子树和右子树构成最后的结果
            for(TreeNode leftSubTree:leftSubTreeList){
                for(TreeNode rightSubTree:rightSubTreeList){
                    TreeNode root=new TreeNode(i);
                    root.left=leftSubTree;
                    root.right=rightSubTree;
                    res.add(root);
                }
            }
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值