【发布时间】:2022-01-25 16:10:19
【问题描述】:
我正在尝试创建一个函数,该函数将返回递归树中的所有叶子。我看到了很多关于它的其他帖子,但我无法将其修改为我自己的代码。我正在尝试像决策树一样。这是我的代码:
class Node:
def __init__(self, data, positive_child=None, negative_child=None):
self.data = data
self.positive_child = positive_child
self.negative_child = negative_child
self.children_list = []
class Decision:
def __init__(self, root: Node):
self.root = root
self.current = root
def collect_leaves(self, node, leafs):
if node is not None:
if len(node.children_list) == 0:
leafs.append(node.data)
for n in node.children_list:
self.collect_leaves(n, leafs)
def return_all_leaves(self):
leafs = []
self.collect_leaves(self.root, leafs)
return leafs
由于某种原因,它只返回根,而不是叶子..
例如:
flu_leaf2 = Node("influenza", None, None)
cold_leaf2 = Node("cold", None, None)
hard_leaf2 = Node("hard influenza", None, None)
headache_node2 = Node("headache", hard_leaf2, flu_leaf2)
inner_vertex2 = Node("fever", headache_node2, cold_leaf2)
healthy_leaf2 = Node("healthy", None, None)
root2 = Node("cough", inner_vertex2, healthy_leaf2)
diagnoser2 = Diagnoser(root2)
diagnoser2.return_all_leaves(self) 应该返回:
['hard influenza', 'influenza','cold','healthy']
【问题讨论】:
-
首先要注意的是你收集的是节点而不是它的数据,这是你的意思吗?
leafs.append(node)而不是leafs.append(node.data) -
嗯,这是真的,但在我改变这个之后,它只附加根而不是叶子(不,我的意思是 node.data)
-
我想我们需要看看
_collect_leaf_nodes -
收集树叶is_collect_leaf_nodes,我只是更改了函数的名称。再次,编辑。很抱歉造成误解。
-
你在
children_list中放了什么东西?
标签: python python-3.x decision-tree