计算树中叶节点数的 Python 程序
当需要计算树中叶节点的数量时,会创建一个“Tree_structure”类,定义添加根值和其他子值的方法。给出了用户可以选择的各种选项。根据用户的选择,对Tree元素进行操作。
以下是相同的演示-
示例
class Tree_structure: def __init__(self, data=None): self.key= data self.children= [] def set_root_node(self, data): self.key= data def add_vals(self, node): self.children.append(node) def search_val(self, key): ifself.key== key: return self for child in self.children: temp = child.search(key) if temp is not None: return temp return None def count_leaf_node(self): leaf_nodes = [] self.count_leaf_node_helper_fun(leaf_nodes) return len(leaf_nodes) def count_leaf_node_helper_fun(self, leaf_nodes): ifself.children== []: leaf_nodes.append(self) else: for child in self.children: child.count_leaf_node_helper_fun(leaf_nodes) tree = None print('Menu (this assumes no duplicate keys)') print('add at root') print('add below ') print('count') print('quit') while True: my_input = input('What operation would you like to perform ? ').split() operation = my_input[0].strip().lower() if operation == 'add': data = int(my_input[1]) newNode = Tree_structure(data) sub_op = my_input[2].strip().lower() if sub_op == 'at': tree = newNode elif sub_op == 'below': my_pos = my_input[3].strip().lower() key = int(my_pos) ref_node = None if tree is not None: ref_node = tree.search_val(key) if ref_node is None: print('No such key.') continue ref_node.add_vals(newNode) elif operation == 'count': if tree is None: print('The tree is empty') else: count = tree.count_leaf_node() print('The number of leaf nodes are : {}'.format(count)) elif operation == 'quit': break输出结果
Menu (this assumes no duplicate keys) add at root add below count quit What operation would you like to perform ? add 78 at root What operation would you like to perform ? add 90 below 78 What operation would you like to perform ? add 8 below 78 What operation would you like to perform ? count The number of leaf nodes are : 2 What operation would you like to perform ? quit
解释
'Tree_structure'类被创建。
它将“键”设置为True并将一个空列表设置为树的子项。
它有一个“set_root”函数,可以帮助设置树的根值。
定义了一个名为“add_vals”的方法,它有助于将元素添加到树中。
定义了另一个名为“search_val”的方法,它有助于搜索树中的元素。
定义了另一个名为“count_leaf_nodes”的方法,它有助于获取树的叶节点数。
定义了另一个名为“count_leaf_nodes_helper”的方法,它调用先前定义的函数——这是一个递归函数。
给出了四个选项,例如“在根目录添加”、“在下面添加”、“计数”和“退出”。
根据用户给出的选项,执行相应的操作。
此输出显示在控制台上。