Go语言递归表现异常?树遍历问题排查及解决
Go语言递归树遍历切片结果为空的问题及解决
我正在学习Go语言准备编程面试,遇到一道LeetCode树遍历题目。用Python递归实现可正常运行,但Go语言表现不同:调用栈逐个弹出时,res切片中的元素会被逐个清空。题目预期结果为[1,3,5,6,2,4],Python能正确返回,但以下Go代码返回[]:
/** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */ func preorder(root *Node) []int { res := []int{} traverse(root, res) return res } func traverse(root *Node, res []int){ if root == nil{ return } res = append(res, root.Val) for _, n := range root.Children{ traverse(n, res) } // 代码执行到此处时,切片的最后一个元素会被移除 }
更新
感谢各位解答,我现在对Go语言中slice的工作原理有了更清晰的理解。以下代码可正常运行:
/** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */ func preorder(root *Node) []int { res := []int{} res = traverse(root, res) return res } func traverse(root *Node, res []int) []int{ if root == nil{ return res } res = append(res, root.Val) for _, n := range root.Children{ res = traverse(n, res) } return res }
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

