【发布时间】:2018-12-26 03:08:02
【问题描述】:
我想把所有节点的值作为数组返回,但是返回值不对。
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]
【问题讨论】:
-
Algorithms + Data Structures = Programs, Niklaus Wirth. 你提供了你的算法。你的数据结构在哪里?
标签: go data-structures binary-tree