golang binaryTree Preorder return 值不正确

golang binaryTree Preorder return value not right

我想return将所有节点的值作为一个数组,但是return值是错误的

type TreeNode struct {
    Left  *TreeNode
    Right *TreeNode
    Val   int
}

type BinaryTree struct {
    Root *TreeNode
}
    func PreorderRecursion(root *TreeNode, result []int) []int {
    if root == nil {
        return nil
    }
    result = append(result, root.Val)
    res1 :=PreorderRecursion(root.Left,result)
    res2 :=PreorderRecursion(root.Right,result)
    result = append(result,res1...)
    result = append(result,res2...)
    return result
}

func TestBinaryTree_PreOrder(t *testing.T) {
    tree := BinaryTree{}
    tree.Root = &TreeNode{Val: 1}
    tree.Root.Left = &TreeNode{Val: 2}
    tree.Root.Right = &TreeNode{Val: 3}

    tree.Root.Left.Left = &TreeNode{Val: 4}
    var result []int
    result =PreorderRecursion(tree.Root,result)
    fmt.Println(result,"----")
}

正确的结果应该是:1 2 4 3

但我明白了:[1 1 2 1 2 4 1 3]

问题源于您将 result 切片传递给递归调用。因此,每个递归调用都会附加上面节点的结果。你期望 1 2 4 3,但你从第一次调用中得到 1,然后从第二次调用中得到 1 2(而不是 2),然后是 1 2 4(而不是仅 4) 来自第三次调用。

要解决此问题,您只需删除将结果切片传递给递归函数即可。该函数应该只为它所在的节点加上它的后代树创建一个结果切片,它不需要知道父节点的结果是什么。

Slices hold references to an underlying array, and if you assign one slice to another, both refer to the same array. If a function takes a slice argument, changes it makes to the elements of the slice will be visible to the caller

查看 Effective Go 中的切片 Slices

PreorderRecursion 不应该接受切片并更改它。这是一种方法。

func PreorderRecursion(root *TreeNode) []int {
    if root == nil {
        return nil
    }
    result := append([]int{}, root.Val)
    res1 := PreorderRecursion(root.Left)
    res2 := PreorderRecursion(root.Right)
    result = append(result, res1...)
    result = append(result, res2...)
    return result
}