[LeetCode_96] Unique Binary Search Trees

题目链接

https://leetcode.com/problems/unique-binary-search-trees/

题意

计算给定节点数的BST有多少种

思路

递归

相关知识

二叉搜索树(Binary Search Tree ,BST)

A BST is defined as follows:
1 The left subtree of a node contains only nodes with keys less than the node's key.
2 The right subtree of a node contains only nodes with keys greater than the node's key.
3 Both the left and right subtrees must also be binary search trees.

特点:
1.每个节点的值大于其任意左侧子节点的值,小于其任意右节点的值。
2.平衡时性能逼近二分查找,但相比连续内存空间的二分查找,插入删除操作开销更小,但多次插入删除可能造成树的不平衡,最坏接近线性查找。

代码

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

reference

https://www.cnblogs.com/Leo_wl/p/5229585.html

posted on 2019-01-22 20:56  coding_gaga  阅读(280)  评论(0编辑  收藏  举报

导航