LeetCode: Unique Binary Search Trees [095]

时间:2022-05-22 08:06:42

【题目】

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,2,3,4,5...n这n个值,能构造多少棵合法的二叉搜索树

【思路】

对于给定[1,n]区间,先确定全部可能的根。如果根为k, 则该二叉树左子树的取值区间为[1, k-1]和右子树的取值区间[k+1, n]。

    而二叉搜索搜索树的随意一个节点的左右子树也是二叉搜索树,因此我们须要确定[1,k-1]和[k+1, n]上构造的二叉搜索树的数目, 比方分别为left[k], right[k]。

则以k的根的二叉搜索树的数目即为,left[k]*right[k]

    

    本题用递归来解决。

【代码】

class Solution {
public: int binaryTreeNums(int start, int end){
//[start, end]区间上构造二叉树的数目
if(start>=end)return 1; //start<end表示空子树, start==end表示叶子节点 int treeNums=0; for(int root=start; root<=end; root++){
int leftCount = binaryTreeNums(start, root-1); //计算左子树的数目
int rightCount = binaryTreeNums(root+1, end); //计算右子树的数目
treeNums+= leftCount*rightCount;
} return treeNums;
} int numTrees(int n) {
if(n==0)return 0;
return binaryTreeNums(1, n);
}
};