怎么说呢,以为这道题不用记录了,菜得吓到了自己。起因是这个遍历的递归一般是写两个函数完成,如下:
func inorder(root *TreeNode, res *[]int) {if root == nil {return}inorder(root.Left, res)*res = append(*res, root.Val) // 注意一下切片指针inorder(root.Right, res)
}func inorderTraversal(root *TreeNode) []int {var res []intinorder(root, &res)return res
}
然后我就想为啥不全局的res,直接一个函数搞定呢:
var res []int
func inorderTraversal(root *TreeNode) []int {if root == nil {return res}inorderTraversal(root.Left)res = append(res, root.Val)inorderTraversal(root.Right)return res
}
当然是错的,因为res在整个程序运行过程中都存在且共享的,每次遍历不同的树之前按理说都应该res = []int{} // 每次调用时重新初始化 res
从测试结果来看,在力扣的测试环境中,全局变量的生命周期是整个测试用例的执行过程。也就是说,全局变量在整个测试过程中只会初始化一次,而不会在每个测试用例之间重新初始化。别用!
如果我就要一个函数搞定呢?闭包(其实在这里就是写个内部函数)闭包Closure是指一个函数(或方法)捕获并持有其外部作用域的变量,即使外部函数已经执行完毕,闭包仍然可以访问和修改这些变量。
func inorderTraversal(root *TreeNode) []int {var res []intvar inorder func(node *TreeNode)// 定义一个闭包(内部函数)inorder = func(node *TreeNode) {if node == nil {return}inorder(node.Left)res = append(res, node.Val) // 访问并修改外部变量 resinorder(node.Right)}inorder(root)return res
}
在 Go 中,闭包通常用于:
函数嵌套(在函数内部定义另一个函数)
访问外部变量(内部函数可以修改外部函数的变量)