Craking The code interview all path sum python

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.