从左向右遍历一个数组,通过不断将其中的元素插入树中可以逐步地生成一棵二叉搜索树。给定一个由不同节点组成的二叉树,输出所有可能生成此树的数组。
示例:
给定如下二叉树
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