Problem:
You is given a binary tree in which each node contains a value. Design a 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 a 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's 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=noneroot=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 solutionif __name__== "__main__": Main ()
Craking The code interview all path sum python