python - 遍历二叉树的递归列表问题
问题描述
我正在尝试使用递归来遍历二叉树。每棵树要么有两个孩子,要么没有孩子(即为孩子保留的字段==无)
我想将每个分支的最终叶子(即两个孩子 == None 的每个节点)添加到列表中,然后返回列表。我正在使用“搜索”功能和助手“search_base”功能来执行此操作。
通过调试器,我看到“搜索”函数中的列表确实包含我想要的元素。但是,当它在 search_base 函数中返回时,结果似乎是一个空列表。
我非常困惑,如果有任何帮助,我将不胜感激。谢谢!
class Node:
def __init__(self, data, pos = None, neg = None):
self.data = data
self.positive_child = pos
self.negative_child = neg
class Diagnoser:
def __init__(self, root):
self.root = root
def search_base(self):
leaf_list=[]
current = self.root
return self.search(current, leaf_list)
def search(self, current, leaf_list):
if(current.positive_child == None):
leaf_list.append(current)
return leaf_list
else:
self.search(current.positive_child, leaf_list)
self.search(current.negative_child, leaf_list)
if __name__ == "__main__":
# Manually build a simple tree.
# cough
# Yes / \ No
# fever healthy
# Yes / \ No
# influenza cold
flu_leaf = Node("influenza", None, None)
cold_leaf = Node("cold", None, None)
inner_vertex = Node("fever", flu_leaf, cold_leaf)
healthy_leaf = Node("healthy", None, None)
root = Node("cough", inner_vertex, healthy_leaf)
diagnoser = Diagnoser(root)
leaf_list = diagnoser.search_base()
print(leaf_list[0].data)
解决方案
问题是在
self.search(current.positive_child, leaf_list)
self.search(current.negative_child, leaf_list)
这些语句的返回值不会被保存或返回,所以这里的函数给出None
. 此外,leaf_list
传递到这两个语句中的值是相同的,即它们不会被连接起来。在递归函数中,最好不要产生副作用以确保其安全。它应该是:
def search(self, current, leaf_list=[]):
if(current.positive_child == None):
return [current]
else:
return (self.search(current.positive_child, leaf_list)
+ self.search(current.negative_child, leaf_list))
推荐阅读
- python - 减少 MFCC 输出
- amazon-web-services - 在本地运行 AWS SAM CLI 时启用 CORS
- spring-data-mongodb - Mongobee MongoQueryException:没有经过身份验证的用户
- angular - How to pass data from one component to another in Angular without creating new instance?
- javascript - 谷歌浏览器错误还是什么?
- c# - c# 按多列分组,然后选择 count > 1 的所有字段
- javascript - 删除多个数组Javascript中重复的所有唯一值
- smartsheet-api - 遍历工作表并附加列
- c - 有人可以帮助解释这个 C 算法在做什么吗?
- c# - 为tabcontrol中的每个tabitem添加多个datatable和tabitem.content