這是我要解決的問題。但是,我無法弄清楚為什么 ans 的指標在遞回函式中發生了變化,但在 main 函式中仍然相同。誰能指出問題出在哪里?
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/solution/
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
另外,我嘗試將 return ans 更改為 return ans.right 并且它有效。仍然不明白為什么它可以作業,但上面的不能作業
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
uj5u.com熱心網友回復:
因為ans在內部函式中是內部函式的區域。您將需要使用成員變數 ( self.ans) 或將其設為兩個函式中的全域變數。
uj5u.com熱心網友回復:
比較這三個例子:
In [32]: def outer():
...: def inner():
...: val = 3
...: print(f"inner val: {val}")
...: val = 0
...: print(f"outer1 val: {val}")
...: inner()
...: print(f"outer2 val: {val}")
...:
In [33]: outer()
outer1 val: 0
inner val: 3
outer2 val: 0
In [34]: def outer():
...: val = 0
...: def inner():
...: val = 3
...: print(f"inner val: {val}")
...:
...: print(f"outer1 val: {val}")
...: inner()
...: print(f"outer2 val: {val}")
...:
In [35]: outer()
outer1 val: 0
inner val: 3
outer2 val: 0
In [36]: def outer():
...: def inner():
...: nonlocal val
...: val = 3
...: print(f"inner val: {val}")
...: val = 0
...: print(f"outer1 val: {val}")
...: inner()
...: print(f"outer2 val: {val}")
...:
In [37]: outer()
outer1 val: 0
inner val: 3
outer2 val: 3
只有最后一個按您希望的方式作業。Python 變數范圍默認是本地的,您需要通過nonlocal宣告明確告訴它在封閉范圍內查找,否則您將定義一個內部函式本地的新變數。
見https://www.education.io/edpresso/the-legb-rule-in-python
所以這應該作業:
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
# the helper dfs function
def dfs(root):
nonlocal ans
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
評論中討論的另一個例子:
In [44]: def outer():
...: def inner():
...: val["a"] = 3
...: print(f"inner val: {val}")
...: val = {"a": 1}
...: print(f"outer1 val: {val}")
...: inner()
...: print(f"outer2 val: {val}")
...:
In [45]: outer()
outer1 val: {'a': 1}
inner val: {'a': 3}
outer2 val: {'a': 3}
在這里我們可以看到nonlocal不需要宣告......對于屬性或專案訪問,Python 似乎會尋找封閉范圍來查找實體。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/489062.html
下一篇:使用java遞回來反轉字串
