I'm trying to create a function that will return all the leaves in my recursive tree. I saw many other posts about it but I couldn't modify it to my own code. I am trying to make like a decision tree. This is my code:
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
from some reason it returns only the root, and not the leaves..
For example:
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)
is supposed to return:
['hard influenza', 'influenza','cold','healthy']