【问题标题】:golang binaryTree Preorder return value not rightgolang binaryTree Preorder 返回值不对
【发布时间】: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]

【问题讨论】:

标签: go data-structures binary-tree


【解决方案1】:

切片保存对底层数组的引用,如果你分配一个 切片到另一个,两者都引用同一个数组。如果一个函数需要一个 切片参数,它对切片元素所做的更改将是 调用者可见

查看 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
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 2016-09-08
      • 2013-07-29
      • 1970-01-01
      • 2023-03-17
      • 2018-08-31
      • 1970-01-01
      相关资源
      最近更新 更多