gpt4 book ai didi

golang binaryTree Preorder返回值不正确

转载 作者:IT王子 更新时间:2023-10-29 02:19:57 25 4
gpt4 key购买 nike

我想以数组的形式返回所有节点的值,但是返回值是错误的。

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]

最佳答案

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 中的 slice Slices

PreorderRecursion 不应获取 slice 并更改它。这是一种方法。

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
}

关于golang binaryTree Preorder返回值不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53927050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com