go语言函数间如何共享变量 发表于 2020-01-21 go语言函数间维护公共变量通常有三种办法: 1.全局变量(此方法在leetcode中老是报错)2.函数内部定义函数,嵌套调用,嵌套的函数可以使用上层的变量3.使用指针,使用指向同一个变量的指针 1.全局变量 1234567891011121314151617181920212223var list []intfunc checkEqualTree(root *TreeNode) bool { total := sum(root) list = list[:len(list)-1] if total%2 == 0 { for _, v := range list { if v == total/2 { return true } } } return false}func sum(root *TreeNode) int { if root == nil { return 0 } tmp := sum(root.Left) + sum(root.Right) + root.Val list = append(list, tmp) return tmp} 2.函数内部定义 12345678910111213141516171819202122func checkEqualTree(root *TreeNode) bool { var list []int var sum func(root *TreeNode)int sum = func(root *TreeNode) int { if root == nil { return 0 } tmp := sum(root.Left) + sum(root.Right) + root.Val list = append(list, tmp) return tmp } total := sum(root) list = list[:len(list)-1] if total%2 == 0 { for _, v := range list { if v == total/2 { return true } } } return false} 3.使用指针 12345678910111213141516171819202122func checkEqualTree(root *TreeNode) bool { list := []int{} total := sum(root, &list) list = list[:len(list)-1] if total%2 == 0 { for _, v := range list { if v == total/2 { return true } } } return false}func sum(root *TreeNode, list *[]int) int { if root == nil { return 0 } tmp := sum(root.Left, list) + sum(root.Right, list) + root.Val *list = append(*list, tmp) return tmp}