Home  >  Article  >  Backend Development  >  Can you explain why variables have different values ​​when they are declared inside a function?

Can you explain why variables have different values ​​when they are declared inside a function?

王林
王林forward
2024-02-12 17:30:06354browse

Can you explain why variables have different values ​​when they are declared inside a function?

Question content

This is the first time I write code. But the value of variable left is always -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
}

After changing the code like this, the left side has the value on the right side.

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's the difference? ? please tell me.

I thought the variable left should have a different value after the recursion, but it doesn't.

Solution

In the first case, the left variable is inside the closure of the inner lambda. This means that the variable is "global" from the function's perspective. Since the lambda is recursive, each call destroys the previous value, which at the end (of the recursion) has a value of -1 (the recursive base case) and never changes thereafter (when returning from the recursion).

In the second case, left is a local variable, which is then pushed or popped onto the stack on each call.

The above is the detailed content of Can you explain why variables have different values ​​when they are declared inside a function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete