從左向右遍歷一個數組,通過不斷將其中的元素插入樹中可以逐步地生成一棵二叉搜索樹。給定一個由不同節點組成的二叉樹,輸出所有可能生成此樹的數組。
示例:
給定如下二叉樹
2
/ \
1 3
返回:
[
[2,1,3],
[2,3,1]
]
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/bst-sequences-lcci
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路:
candidates 數組保存下一步能夠移動到的所有節點,按照全排列的解法往下走。
func BSTSequences(root *TreeNode) [][]int {
res := make([][]int, 0)
candidates := []*TreeNode{}
if root != nil {
candidates = append(candidates, root)
}
run(candidates, []int{}, &res)
return res
}
func run(candidates []*TreeNode, t []int, res *[][]int) {
if len(candidates) == 0 {
*res = append(*res, t)
return
}
for ind,v := range candidates {
//排除v這個節點
newlist := append(candidates[:0:0],candidates[:ind]...)
newlist = append(newlist, candidates[ind+1:]...)
//保存v可以去的下一個節點
if v.Left != nil {
newlist = append(newlist, v.Left)
}
if v.Right != nil {
newlist = append(newlist, v.Right)
}
// p := append(t[:0:0], t...)
p := make([]int,len(t))
copy(p,t)
p = append(p, v.Val)
run(newlist, p, res)
}
}