Could you explain why variable has different value when declare variable inside of function?

huangapple go评论67阅读模式
英文:

Could you explain why variable has different value when declare variable inside of function?

问题

第一次写的代码中,变量left始终具有值-1

第二次修改后的代码中,left有正确的值。

两者的区别是在第一次写的代码中,left是一个全局变量,而在第二次修改后的代码中,left是在每次递归调用时重新声明的局部变量。

在第一次写的代码中,left的值在每次递归调用时都会被覆盖为新的值,因此最终只会保留最后一次递归调用的结果。而在第二次修改后的代码中,每次递归调用都会创建一个新的局部变量left,因此每个递归调用都会有自己的left值,不会相互干扰。

所以,第二次修改后的代码中的left变量会有不同的值,而第一次写的代码中的left变量始终为-1

英文:

At the first time, I write code like this. but variable left always has value -1.

func diameterOfBinaryTree(root *TreeNode) int {
	var longest int
    var left int
    var right int
	max := func(a, b int) int {
		if a > b {
			return a
		}
		return b
	}
	var dfs func(*TreeNode) int
	dfs = func(node *TreeNode) int {
		if node == nil {
			return -1
		}
		left = dfs(node.Left)
		right = dfs(node.Right)

		longest = max(longest, left+right+2)
		return (max(left, right) + 1)
	}
	dfs(root)
	return longest
}

and after change code like this, left has right value.

func diameterOfBinaryTree(root *TreeNode) int {
	var longest int
	max := func(a, b int) int {
		if a > b {
			return a
		}
		return b
	}
	var dfs func(*TreeNode) int
	dfs = func(node *TreeNode) int {
		if node == nil {
			return -1
		}
		left := dfs(node.Left)
		right := dfs(node.Right)

		longest = max(longest, left+right+2)
		return (max(left, right) + 1)
	}
	dfs(root)
	return longest
}

what is difference ?? please let me know.

I think variable left should have different value after recursion but not.

答案1

得分: 1

在第一种情况下,left变量位于内部lambda函数的闭包中。这意味着从函数的角度来看,这个变量是“全局”的。由于lambda函数是递归的,每次调用都会覆盖先前的值,在递归的末尾(递归基本情况)其值为-1,并且在递归返回时不会再改变。

在第二种情况下,left是一个局部变量,每次调用时都会被推入/弹出堆栈。

英文:

In the first case, the left variable is in the closure of the inner lambda. That means that this variable is "global" from the point of view of the function. As the lambda is recursive, each call crushes the previous value, at the end (of the recursion) its value is -1 (the recursion base case) and never changed after (when going back from the recursion).

In the second case, left is a local variable and then pushed/popped to/from the stack at each call.

huangapple
  • 本文由 发表于 2023年6月21日 12:35:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76519975.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定