Python程式計算給定樹的非葉子節點數
當需要查詢樹中非葉子節點的數量時,會建立一個名為“Tree_structure”的類,定義設定根值和新增其他值的方法。提供了使用者可以選擇的多項選項。根據使用者的選擇,對樹元素執行操作。
以下是相同的演示 -
示例
class Tree_structure: def __init__(self, data=None): self.key = data self.children = [] def set_root(self, data): self.key = data def add_vals(self, node): self.children.append(node) def search_val(self, key): if self.key == key: return self for child in self.children: temp = child.search_val(key) if temp is not None: return temp return None def count_non_leaf_node(self): nonleaf_count = 0 if self.children != []: nonleaf_count = 1 for child in self.children: nonleaf_count = nonleaf_count + child.count_non_leaf_node() return nonleaf_count tree = None print('Menu (this assumes no duplicate keys)') print('add <data> at root') print('add <data> below <data>') 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) suboperation = my_input[2].strip().lower() if suboperation == 'at': tree = newNode elif suboperation == 'below': position = my_input[3].strip().lower() key = int(position) 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_non_leaf_node() print('The number of non-leaf nodes are : {}'.format(count)) elif operation == 'quit': break
輸出
Menu (this assumes no duplicate keys) add <data> at root add <data> below <data> count quit What operation would you like to perform ? add 34 at root What operation would you like to perform ? add 78 below 34 What operation would you like to perform ? add 56 below 78 What operation would you like to perform ? add 90 below 56 What operation would you like to perform ? count The number of non-leaf nodes are : 3 What operation would you like to perform ? quit
解釋
建立“Tree_structure”類。
它將“key”設定為True,並將一個空列表設定為樹的子節點。
它有一個“set_root”函式,有助於設定樹的根值。
定義了一個名為“add_vals”的方法,有助於向樹中新增元素。
定義了一個名為“search_val”的方法,有助於在樹中搜索元素。
定義了一個名為“count_non_leaf_nodes”的方法,有助於獲取樹的非葉子節點的數量。
這是一個遞迴函式。
提供了四個選項,例如“新增到根節點”、“新增到下方”、“計數”和“退出”。
根據使用者提供的選項,執行相應操作。
此輸出顯示在控制檯上。
廣告