craking the code interview all path sum python

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()


你可能感兴趣的:(python,cc150)