[Leetcode]Unique Binary Search Trees I & II

I

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+1的count数组,count[i]表示数0-i一共能产生多少个不同的BST。

这里我们要深刻理解BST的一个性质,即BST的任意子树依然是个BST

显然的,我们可以发现:

count[0] = 1 空树

count[1] = 1 只有1节点的树

在观察count[2],我们发现可以这样计算count[2]:

选择1做根节点, 由于BST的性质,其左子树只能是空树,只有count[0]种可能,右子树是由节点2组成的树,一共有count[1]种可能。

选择2做根节点,同理可得左子树有count[1]种,右子树有count[0]种。

因此count[2] = count[0] * count[1] + count[1] * count[0]


通过这个分析,我们可以发现其实判断有多少unique BST就是让每个树做根节点一次,计算他得左子树数目和右子树数目,然后相乘即可。

因此其Count[i] = ∑ Count[0...k] * [ k+1....i]


public int numTrees(int n) {
        int[] count = new int[n + 1];
        count[0] = 1;
        count[1] = 1;
        
        for (int i = 2; i <= n; i++) 
            for (int j = 0; j < i; j++) {
                count[i] += count[j] * count[i - 1 - j];
            }
        
        return count[n];
    }

 

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


II 的思路和I类似,用同样的递归思路来做。

public List<TreeNode> generateTrees(int n) {
        return generateTrees(1, n);
    }
    
    private List<TreeNode> generateTrees(int start, int end) {
        List<TreeNode> list = new ArrayList<TreeNode>();
        if (start > end) {
            list.add(null);
            return list;
        }
        
        for (int i = start; i <= end; i++) {
            List<TreeNode> lefts = generateTrees(start, i - 1);
            List<TreeNode> rights = generateTrees(i + 1, end);
            for (TreeNode left: lefts) {
                for (TreeNode right: rights) {
                    TreeNode root = new TreeNode(i);
                    root.left = left;
                    root.right = right;
                    list.add(root);
                }
            }
        }
        return list;
    }




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值