我想将所有节点的值作为一个数组返回,但是返回值是错误的。
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]
繁花不似锦
幕布斯6054654
相关分类