Python程序:查找树中所有节点的和

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_values(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(key)
         if temp is not None:
            return temp
      return None

   def summation_nodes(self):
      sum_val = self.key
      for child in self.children:
         sum_val = sum_val + child.summation_nodes()
      return sum_val

tree = None

print('Menu (no duplicate keys allowed)')
print('add <data> at root')
print('add <data> below <data>')
print('summation')
print('quit')

while True:
   my_input = input('What would you like to do? ').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 exists')
            continue
         ref_node.add_values(newNode)

   elif operation == 'summation':
      if tree is None:
         print('The tree is empty')
      else:
         summation_val = tree.summation_nodes()
         print('Sum of all the nodes is : {}'.format(summation_val))

   elif operation == 'quit':
      break

输出

菜单(不允许重复键)
在根处添加
在下添加
求和
退出
What would you like to do? 添加56到根
What would you like to do? 在56下面添加45
What would you like to do? 在56下面添加23
What would you like to do? 求和
所有节点的总和为:124
What would you like to do?

解释

  • 创建了“Tree_structure”类。

  • 将“key”设置为True,并将树的孩子列表设置为空列表。

  • 它有一个‘set_root’函数,可以设置树的根值。

  • 定义了一个名为‘add_vals’的方法,可帮助将元素添加到树中。

  • 另一个名为‘search_val’的方法被定义,可帮助搜索树中的元素。

  • 另一个名为‘somation_nodes’的方法已截断,继续输出:

定义,用于获取树的所有元素/节点的总和。它是一个递归函数。

  • 给出了四个选项,如“在根下添加”、“在下面添加”、“求和”和“退出”。

  • 根据用户给出的选项,执行相应的操作。

  • 输出在控制台上显示。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程