首页 > 代码库 > LeetCode:Unique Binary Search Trees

LeetCode: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作为根节点。当以i作为跟节点时,其左子树节点数为i-1,右子树的节点数为n-i。以同样的方法递归地求左子树和右子树可能形成的二分查找树的个数为leftSubTree和rightSubTree。则以i做为根节点时所能形成的二分查找树的个数为leftSubTree*rightSubTree。将各节点的leftSubTree*rightSubTree求和既得所求。

代码:

public class Solution {
    public int numTrees(int n) {
       int sum = 0;
       int i;
       if(n == 0 || n == 1)
           return 1;
       for(i = 1;i <= n;i++)
       {
           int leftSubTree = numTrees(i - 1);
           int rightSubTree = numTrees(n - i);
           sum = sum + leftSubTree * rightSubTree;
       }
       return sum;
    }
}








LeetCode:Unique Binary Search Trees