Unique Binary Search Trees
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
思路
n个点中每个点都可以作为root,当i作为root时,小于i的点都只能放在其左子树中,大于i的点只能放在右子树中,此时只需求出左、右子树各有多少种,二者相乘即为以i作为root时BST的总数。
解题
c++版
1 | class Solution { |
python版
1 | class Solution: |