使用递归前序遍历二叉树的一点问题
def preorder(self,root): # 先序遍历(递归)
if root is None:
return []
result = [root.item]
left_item = self.preorder(root.left_child)# 先遍历完左子树的所有左子树
right_item = self.preorder(root.right_child)
return result + left_item + right_item
在遍历完左子树的所有左子树后,进入 right_item = self.preorder(root.right_child) 。这个时候,已经遍历过的节点值自动成为了一个列表,让我很奇怪。return语句也是在left_item和right_item语句执行完毕之后才执行的,应该没有地方可以合并列表才对。
如果改成
def preorder(self,root):
if root is None:
return []
print= root.item # 这样就比较直观,可以得到一个节点的值,就打印出来,是合理的
left_item = self.preorder(root.left_child)
right_item = self.preorder(root.right_child)
return result + left_item + right_item
就更容易一点