95. 不同的二叉搜索树 II
2019-04-25 本文已影响0人
one_zheng
给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树。
示例:

// 用递归的思想,[1,n]的所有二叉树肯定是1+[2,n]的二叉树加 [1]+2+[3,n]的二叉树加[1,n-1]+n的二叉树,由此递归即可
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func generateTrees(n int) []*TreeNode {
return generateTree(1, n)
}
func generateTree(l, r int) []*TreeNode {
res := make([]*TreeNode, 0)
if r-l == 1 {
root1 := &TreeNode{
Val: l,
Right: &TreeNode{
Val: r,
},
}
root2 := &TreeNode{
Val: r,
Left: &TreeNode{
Val: l,
},
}
res = append(res, root1, root2)
return res
} else if r-l == 0 {
res = append(res, &TreeNode{
Val: l,
})
return res
} else if r-l > 1 {
for i := l; i <= r; i++ {
lchild := generateTree(l, i-1)
rchild := generateTree(i+1, r)
if len(lchild) > 0 && len(rchild) > 0 {
for j := 0; j < len(lchild); j++ {
for k := 0; k < len(rchild); k++ {
root := new(TreeNode)
root.Val = i
root.Left = lchild[j]
root.Right = rchild[k]
res = append(res, root)
}
}
} else if len(lchild) > 0 {
for k := 0; k < len(lchild); k++ {
root := new(TreeNode)
root.Val = i
root.Left = lchild[k]
res = append(res, root)
}
} else if len(rchild) > 0 {
for k := 0; k < len(rchild); k++ {
root := new(TreeNode)
root.Val = i
root.Right = rchild[k]
res = append(res, root)
}
}
}
return res
}
return res
}