第六题 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

Note:

Binary Search Tree的特点:左边的分支只能存比root小的数,右边的分支只能存比root大的数。

所以每选定一个根节点,相当于将其余的n-1个数分成了两组,一组比根节点小,一组比根节点大。所以可以用递归解题。


Solution in Java 1:递归实现

public class Solution {

    public int numTrees(int n) {

        int sol =0;

        if(n==0) return 1;

        if(n==1) return 1;

        

        for(int i=0; i<n; i++){

            sol = sol+numTrees(i)* numTrees(n-i-1);

        }

        return sol;

     }

     

}

注意左边分支和右边分支的解法应相乘得到一个选定root的解法总和。因为一个分支没有节点和只有一个节点都是一种解法,所以有初始条件:  if(n==0) return 1;

if(n==1) return 1;

 Solution in Java 2:Dynamic Programming 

重复利用底层计算结果,节省一些时间。用数组solu[n+1]来储存中间计算结果。

故solu[i]表示含有i个结点的BST有多少个独特构造。故结果储存在solu[n]中。

public class Solution {
    public int numTrees(int n) {
        int[] solu = new int[n+1];
        solu[0] = 1;    //branch has 0 node, 1 unique BST
        solu[1] = 1;    //branch has 1 node, 1 unique BST
        for(int i=2; i<n+1; i++){
            for(int j=0; j<i; j++){     //j is the number of nodes in the left subtree, 
                                        //the max value of j is i-1 because there is 1 node to be root
                solu[i] += solu[j]*solu[i-j-1];  //root has 1 node, left subtree has j nodes, so right subtree has i-j-1 nodes.
            }
        }
        return solu[n];
    }
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值