[英]Trouble following the call stack in a Binary Search Tree Inorder Tree Traversal call
我希望有人能為我澄清這個遞歸調用中調用堆棧的工作原理。 我想我開始考慮遞歸和回溯,這對我來說一直是個問題,我認為我已經將問題縮小到一個特定的領域。
因此,當我在 Python 中練習 BST 中序遍歷時,就出現了困惑。
這是我用來表示以下數組 [10, 14, 19, 27, 31, 35, 42] 的 BST 樹的實現。
我提供了 3 個中序遍歷解決方案,因為我試圖了解遞歸調用堆棧是如何工作的。 對於選項 1 和 2,當我將結果保留在遞歸調用之外時,我會了解解決方案的工作原理。 但是對於選項 3,當我們執行 res = 和 res = res + 時,我很困惑調用堆棧如何跟蹤它以返回答案。 我想一旦我了解了 res 如何保存在調用堆棧中,我將能夠理解遞歸是如何工作的。 有人可以告訴我這是如何工作的嗎?
僅供參考:我沒有運行與所有三個函數命名相同的解決方案,因為它是為了示例。
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
node = Node(data)
if self.data:
if data < self.data:
if self.left is None:
self.left = node
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = node
else:
self.right.insert(data)
else:
self.data = data
def printTree(self):
if self.left:
self.left.printTree()
print(self.data)
if self.right:
self.right.printTree()
# Option 1) I can follow the call stack if I implement it like this keeping the result out of the helper function
def inorderTraversalRecursive(self, root):
res = []
def inorder(root):
if not root:
return
inorder(root.left)
res.append(root.data)
inorder(root.right)
inorder(root)
return res
# Option 2) I can also follow the stack when I implement it like this and print the root with end=''
def inorderTraversalRecursive(self, root):
if root is None:
return
self.inorderTraversalRecursive(root.left)
print(root.data, end=' ')
self.inorderTraversalRecursive(root.right)
# Option 3) I have an issue understanding once I put the result into the if root statement
def inorderTraversalRecursive(self, root):
res = []
if root:
res = self.inorderTraversalRecursive(root.left)
res.append(root.data)
res = res + self.inorderTraversalRecursive(root.right)
return res
#Creating the Tree
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(31)
root.insert(42)
print(root.inorderTraversalRecursive(root))
以下是我重寫函數的方式,希望它有助於更好地理解它:
def inorderTraversalRecursive(self, root):
if root:
return self.inorderTraversalRecursive(root.left)\
+[root.data]\
+self.inorderTraversalRecursive(root.right)
return []
PS1。 在您的代碼中,函數的名稱(變體 3)是inorderTraversal
- 可能是拼寫錯誤。
PS2。 我想知道為什么insert
函數中有if self.data:
塊。 如果self.data
設置為0
它不會被記錄?
PS3。 我希望我做的一切都是正確的。 我敢說,遞歸是一個很棘手的主題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.