刷题遇到的语法错误
错误写法:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func pathSum(root *TreeNode, targetSum int) (ans [][]int) {
path := []int{}
var dfs func(*TreeNode, int)
dfs = func(node *TreeNode, left int) {
if node == nil {
return
}
left -= node.Val
path = append(path, node.Val)
defer func() { path = path[:len(path)-1] }()
if node.Left == nil && node.Right == nil && left == 0 {
//append([]int(nil), path...)实现了将path打散,然后传入新创建的切片[]int(nil)里
//然后将这个切片传入ans这个二维切片里
ans = append(ans, append([]int(nil), path...))
return
}
dfs(node.Left, left)
dfs(node.Right, left)
}(root,targetSum)
//dfs(root, targetSum)
return
}
这么写:匿名函数后面加(参数),是调用了,然后前面又赋给dfs,所以匿名函数得有返回值,所以出现了报错:
Line 28: Char 6: (func literal)(root, targetSum) used as value (solution.go)
正确写法如下:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func pathSum(root *TreeNode, targetSum int) (ans [][]int) {
path := []int{}
var dfs func(*TreeNode, int)
dfs = func(node *TreeNode, left int) {
if node == nil {
return
}
left -= node.Val
path = append(path, node.Val)
defer func() { path = path[:len(path)-1] }()
if node.Left == nil && node.Right == nil && left == 0 {
//append([]int(nil), path...)实现了将path打散,然后传入新创建的切片[]int(nil)里
//然后将这个切片传入ans这个二维切片里
ans = append(ans, append([]int(nil), path...))
return
}
dfs(node.Left, left)
dfs(node.Right, left)
}
dfs(root, targetSum)
return
}
博客内容讲述了在解决Go语言刷题时遇到的语法错误,主要问题在于匿名函数的使用。作者指出,错误地将匿名函数直接用作值导致了编译错误。通过调整代码,将匿名函数定义为一个独立的函数,并进行调用,成功解决了问题。修正后的代码能正确地遍历二叉树并找到路径和目标和。
3797

被折叠的 条评论
为什么被折叠?



