douzhuan1169 2018-12-26 03:08
浏览 61
已采纳

golang binaryTree预购返回值不正确

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]

  • 写回答

2条回答 默认 最新

  • duanboshe0001 2018-12-26 09:45
    关注

    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

    see slices in Effective Go Slices

    PreorderRecursion shouldn't take in a slice and change it. Here's an approach.

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题