这个问题可能与 this one 类似,但有细微的差别。我想了解当有两个递归调用一个在另一个下面时递归是如何工作的。
考虑以下树遍历进行预排序。
我添加了一些打印语句来了解每个递归调用的工作原理:
from Node import Node
from BinarySearchTree import BinarySearchTree
def preOrderPrint(node):
if node is not None:
print(node.val)
preOrderPrint(node.leftChild)
print('Done with left node')
preOrderPrint(node.rightChild)
print('Done with right node')
BST = BinarySearchTree(6)
BST.insert(4)
BST.insert(9)
BST.insert(5)
BST.insert(2)
BST.insert(8)
BST.insert(12)
preOrderPrint(BST.root)
输出如下:
6
4
2
Done with left node
Done with right node
Done with left node
5
Done with left node
Done with right node
Done with right node
Done with left node
9
8
Done with left node
Done with right node
Done with left node
12
Done with left node
Done with right node
Done with right node
Done with right node
这是我的理解和问题:
因此,基本情况是递归在节点为 None 时终止。左边的递归首先发生,并在它沿着树向下时打印出节点。一旦它到达 2 的左节点,它就会终止。这在“Done with left node”的打印状态中显示。
右边的递归接管。最后访问的节点是 2,所以它从那里开始。它终止是因为 2 的右孩子是 None。这显示在“Done with right node”的打印语句中。
现在,右递归上升到 4。问题:为什么代码在打印 5 之前打印“Done with left node”而不再次打印 2? 它如何知道左节点有完成了吗?你能解释一下递归使用的堆栈吗?或任何其他方式。
答案 0 :(得分:0)
就像我的评论所暗示的那样,您不仅要为叶节点打印“done with ...”;相反,您正在为树中的每个节点执行此操作,甚至是中间节点。
为了更清楚地看到这一点,我建议按如下方式更改您的函数:
def preOrderPrint(node):
if node is not None:
print(node.val)
preOrderPrint(node.leftChild)
print('Done with left node of node', node.val)
preOrderPrint(node.rightChild)
print('Done with right node of node', node.val)
您的输出现在应该是:
6
4
2
Done with left node of node 2
Done with right node of node 2
Done with left node of node 4
5
...