给定一个值n,能构建出多少不同的值包含1...n的二叉搜索树(BST)?
例如
给定 n = 3, 有五种不同的二叉搜索树(BST)
思路:指定头结点,递归调用判断下面还有中方式。如果元素个数是1或者0,直接返回1
func numTrees(n int) int {
// write code here
var num []int
for i := 1; i <= n; i++ {
num = append(num, i)
}
return GetTreeNum(num)
}
func GetTreeNum(num []int) int {
if len(num) == 0 || len(num) == 1 {
return 1
}
var treeNum = 0
for k, _ := range num {
leftNum := GetTreeNum(num[:k])
rightNum := GetTreeNum(num[k+1:])
treeNum += leftNum * rightNum
}
return treeNum
}