Python 我不知道';我不明白这个递归如何打印树
我一直在练习数据结构,我能够插入节点并显示,但我不能理解用于显示树的递归Python 我不知道';我不明白这个递归如何打印树,python,recursion,binary-search-tree,Python,Recursion,Binary Search Tree,我一直在练习数据结构,我能够插入节点并显示,但我不能理解用于显示树的递归 class node: def __init__(self, data=None): self.data = data self.right = None self.left = None class Binary_search_tree: def __init__(self): self.root = None self.
class node:
def __init__(self, data=None):
self.data = data
self.right = None
self.left = None
class Binary_search_tree:
def __init__(self):
self.root = None
self.i = 0
def insert(self, value):
if self.root == None:
self.root = node(value)
else:
self._insert(value, self.root)
def _insert(self, value, current_node):
if value > current_node.data:
if current_node.right == None:
current_node.right = node(value)
else:
self._insert(value, current_node.right)
elif current_node.data > value:
if current_node.left == None:
current_node.left = node(value)
else:
self._insert(value, current_node.left)
def display(self):
if self.root != None:
self._display(self.root)
def _display(self, current_node):
if current_node != None:
self._display(current_node.left)
print(current_node.data)
self._display(current_node.right)
我已经做了尽可能多的演练,但我最终得到了None循环,我不知道它是如何进一步进行的
def _display(self, current_node):
if current_node != None:
self._display(current_node.left)
print(current_node.data)
self._display(current_node.right)
\u display()
函数正在使用。下面是一个3分钟的youtube视频,解释了顺序树遍历:我知道顺序树遍历是如何工作的,只是我不知道递归是如何工作的here@Chandru-有很好的解释。您可以将\u display()
函数的每次调用视为可能创建执行的深层通道,因为对\u display()
的调用可能会产生新的\u display()
执行,而这反过来可能会产生新的\u display()
执行。。。等等最后,对\u display()
的调用不会重新启动并返回,即当前节点!=None
为false,在最近调用\u display()
之后,在语句处继续执行。感谢@BithikaMookherjee,隧道类比是直观的