您的位置:首页 > 产品设计 > UI/UE

(leetcode )Unique Binary Search Trees

2014-09-20 13:03 253 查看
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


解题思路: 不用区分左右树的节点,拿出一个做根节点,左右子树分不同数目的节点即可。

和之前做的二叉树问题不一样,计算结果不要在函数里面用引用 

class Solution {
public:
    int numTrees(int n) {
        int tmp=0;
        if(n ==0 || n ==1) return 1;
        if(n == 2) return 2;
        if(n == 3) return 5;
        for(int i = 0 ; i < n ; i++){
            tmp+= numTrees(i)*numTrees(n-1-i);
        }
        return tmp;
    }
};


再做这个题就没怎么有印象了,这次的解法显然不如上面的好~~没有利用给出2、3个节点的个数信息。

class Solution {
    int bst(int left, int right){
        if(left > right)
            return 1;
        if(left == right)
            return 1;
        int root;
        int ans = 0 ;
        for(root=left; root<=right;root++){
            ans += bst(left,root-1)*bst(root+1,right);
        }
        return ans;
    }
public:
    int numTrees(int n) {
        return bst(0,n-1);
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: