[Python] python pointer is not changed in recursive function

Discussão em 'Python' iniciado por Stack, Junho 8, 2025.

  1. Stack

    Stack Membro Participativo

    This is the problem that I want to solve. However, I cannot figure out why the pointer of ans is changed in recursion function but is still the same in the main function. Could anyone points out where the problem is?

    LeetCode problem: Find a Corresponding Node of a Binary Tree in a Clone of That Tree

    class Solution:
    def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
    # the helper dfs function
    def dfs(root):
    if not root: return
    if root.val == target.val:
    ans = root
    return
    dfs(root.left)
    dfs(root.right)

    # main function
    ans = TreeNode(0)
    dfs(cloned)
    return ans


    Also, I have tried changing return ans to return ans.right and it works. Still don't understand why it works but the upper one cannot work

    class Solution:
    def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
    # the helper dfs function
    def dfs(root):
    if not root: return
    if root.val == target.val:
    ans.right = root
    return
    dfs(root.left)
    dfs(root.right)

    # main function
    ans = TreeNode(0)
    dfs(cloned)
    return ans.right

    Continue reading...

Compartilhe esta Página