python3实现在二叉树中找出和为某一值的所有路径(推荐)

yipeiwu_com7年前Python基础

请写一个程序创建一棵二叉树,并按照一定规则,输出二叉树根节点到叶子节点的路径。

规则如下:

1、从最顶端的根结点,到最下面的叶子节点,计算路径通过的所有节点的和,如果与设置的某一值的相同,那么输出这条路径上的所有节点。

2、从根节点遍历树时,请请按照左到右遍历,即优先访问左子树的节点。

二叉树创建规则:从上到下一层一层的,按照从左到右的顺序进行构造

输入"10,5,12,4,7"值,构造的树如下:

1) 10
2) 10
      /
    5

3) 10
       /\
     5 12
4) 10
        /\
      5 12
     /
   4

5) 10
        /\
      5 12
      /\
     4 7

针对上面的二叉树,如果当前我们设置的“路径和”为19,那么输出结果为:
10,5,4

如果有多个路径,按到左到右的顺序遍历生成的结果每行显示一个显示。例如如果当前我们设置的“路径和”为22,那么

输出结果为:

10,5,7
10,12

如果没有找到路径和为设置的值的路径,输出error。

三、输入:

输入整数N---路径和
一行字符串,多个正整数,之间用","隔开

四、输出: 满足条件的二叉树路径

五、样例输入:

22
10,5,12,4,7

六、样例输出:

10,5,7
10,12

demo:

class Node(object):
  def __init__(self, x):
   self.val = x
   self.left = None
   self.right = None
class Tree(object):
 lt = [] # 依次存放左右孩子未满的节点
 def __init__(self):
   self.root = None
 def add(self, number):
   node = Node(number) # 将输入的数字节点化,使其具有左右孩子的属性
   if self.root == None:
     self.root = node
     Tree.lt.append(self.root)
   else:
     while True:
       point = Tree.lt[0] # 依次对左右孩子未满的节点分配孩子
       if point.left ==None:
         point.left = node
         Tree.lt.append(point.left) # 该节点后面作为父节点也是未满的,也要加入到列表中。
         return
       elif point.right ==None:
         point.right = node
         Tree.lt.append(point.right) # 与左孩子同理
         Tree.lt.pop(0) # 表示该节点已拥有左右孩子,从未满列表中去除
         return
class Solution:
 def __init__(self):
   self.results = []
 def RecursionFindPath(self, root, expectNumber, result):
   result.append(root.val)
   if root.left == None and root.right == None and sum(result) == expectNumber:
     self.results.append(result)
   temp = result[:]
   if root.left:
     self.RecursionFindPath(root.left, expectNumber, result)
   result = temp[:]
   if root.right:
     self.RecursionFindPath(root.right, expectNumber, result)
 def FindPath(self, root, expectNumber):
   if root == None:
     return []
   self.RecursionFindPath(root, expectNumber, [])
   self.results = sorted(self.results, key=len, reverse=True)
   return self.results
if __name__ =='__main__':
 t = Tree() # 二叉树类的实例化
 L = [10, 5, 12, 4, 7]
 for i in L:
   t.add(i)
 expectNum = 22
 print(Solution().FindPath(t.root, expectNum))

输出样例:

总结

以上所述是小编给大家介绍的python3实现在二叉树中找出和为某一值的所有路径,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

分享一个常用的Python模拟登陆类

代码非常简单,而且注释也很详细,这里就不多废话了 tools.py # -*- coding:utf8 -*- ''' # =============================...

Python读写zip压缩文件的方法

Python 内置的 zipfile 模块可以对文件(夹)进行ZIP格式的压缩和读取操作。要进行相关操作,首先需要实例化一个 ZipFile 对象。ZipFile 接受一个字符串格式压缩...

彻彻底底地理解Python中的编码问题

Python处理文本的功能非常强大,但是如果是初学者,没有搞清楚python中的编码机制,也经常会遇到乱码或者decode error。本文的目的是简明扼要地说明python的编码机制,...

使用rpclib进行Python网络编程时的注释问题

rpclib 是一个非常好用的 python webservice 库,可以动态的生成 wsdl, 不过这个项目已经基本停止,并被一个新的项目取代 spyne,由于旧的项目 工作已经比较...

对python函数签名的方法详解

函数签名对象,表示调用函数的方式,即定义了函数的输入和输出。 在Python中,可以使用标准库inspect的一些方法或类,来操作或创建函数签名。 获取函数签名及参数 使用标准库的sig...