Problem:
You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum to a given value. The path does not need to start or end at the root or a leaf.
This is actually an level order traversal problem. We need to store the level value together and then calculate the summation of level up and level down together.
Here is the same test case as above tree problems in cc150.
class ListNode:
def __init__(self,val):
self.val=val
self.next=None
class TreeNode:
def __init__(self,val):
self.val=val
self.left=None
self.right=None
root=TreeNode(0)
root.left=TreeNode(1)
root.right=TreeNode(2)
root.left.left=TreeNode(3)
root.left.right=TreeNode(4)
root.left.left.left=TreeNode(5)
root.right.left=TreeNode(8)
root.right.right=TreeNode(9)we build the function
def levelorder(root,solution,path,level,target):
if root==None:
return
path[level]=root.val
temp=[]
i=level
while i>=0:
temp=temp+[path[i]]
if sum(temp)==target:
solution.append(temp)
i-=1
levelorder(root.left,solution,path,level+1,target)
levelorder(root.right,solution,path,level+1,target)
def main():
solution=[]
path={}
levelorder(root,solution,path,0,4)
print solution
if __name__=="__main__":
main()
本文介绍了一种用于寻找二叉树中所有路径之和等于特定目标值的算法。该算法采用层次遍历的方式,并在遍历过程中计算路径值,以确保能够找到所有符合条件的路径,这些路径不必从根节点开始或在叶节点结束。
361

被折叠的 条评论
为什么被折叠?



