I want to return the values of all nodes as an array, but the return value is wrong.
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,"----")
}
right result should be : 1 2 4 3
but i get this:[1 1 2 1 2 4 1 3]