Python算法和数据结构：在二叉树中找到和为sum的所有路径

[10,5,4,None,3,None,None,7,None,None,12,None,None]

"""

"""
class TreeNode:
"""
树的节点定义，后面的很多操作都是基于节点的
"""

def __init__(self):
"""
定义一个树的节点，初始状态左右节点为空
"""
self.leftNode = None
self.rightNode = None

def setData(self, data):
"""
设置数字的方法
args: data节点值
"""
self.data = data

def setLeftNode(self, leftNode):
"""
设置左节点的方法
args: leftNode 左节点
"""
self.leftNode = leftNode

def setRightNode(self, rightNode):
"""
设置右节点的方法
args: rightNode 右节点
"""
self.rightNode = rightNode

def getData(self):
"""
获取节点数字
return:返回节点数字
"""
return self.data

def getLeftNode(self):
"""
获取左节点
return:返回左节点
"""
return self.leftNode

def getRightNode(self):
"""
获取右节点
return:返回右节点
"""
return self.rightNode

class test:
def __init__(self):
"""
test类的初始化，用来构造树和调用查找算法
return:返回右节点
"""
#self.tree = self.build_tree()
self.index = 0
self.data = [10,5,4,None,3,None,None,7,None,None,12,None,None]
self.tree = self.build_node()
tempNode = self.tree
data_list = []
self.findSum(tempNode, 22, data_list)

def build_node(self):
"""
根据输入，用递归的方法，构造树的方法

"""
if self.index < len(self.data):
curr_data = self.data[self.index]
self.index = self.index + 1
if curr_data != None:
onNode = TreeNode()
onNode.setData(curr_data)
left_node = self.build_node()
onNode.setLeftNode(left_node)
right_node = self.build_node()

onNode.setRightNode(right_node)
return onNode

def findSum(self,node, needsum, data_list):
"""
递归调用findSum,查找和是needsum的路径
args:node是树的根节点，每次递归的是节点移动
needsum是需要求的和
data_list里面存的是路径

"""
if node != None and node.getData() <= needsum :
if node.getData() < needsum:
#print node.getData()
newSum = needsum - node.getData()
curr_data = node.getData()
data_list.append(curr_data)
self.findSum(node.getLeftNode(), newSum, data_list)
self.findSum(node.getRightNode(), newSum, data_list)
data_list.pop()

else:
#开始打印输出路径
if node.getData() == needsum:
for d in data_list:
print d
print node.getData()
print '-----------'

if __name__ == "__main__":
onNode = test()



10

5

4

3

10

5

7

10

12

posted @ 2018-08-28 14:05  玄魂  阅读(641)  评论(0编辑  收藏  举报