码迷,mamicode.com
首页 > 编程语言 > 详细

craking the code interview all path sum python

时间:2015-01-21 09:01:33      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:python   cc150   

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


craking the code interview all path sum python

标签:python   cc150   

原文地址:http://blog.csdn.net/hyperbolechi/article/details/42962337

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!