[Leetcode] Binary tree-- 113. Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]

 

Solution:

 Here I use iterative way,  BFS search

 record the node and the path node value starting from its parent to itself while traversing

 1 if root is None:
 2             return []
 3         
 4         d = []
 5         s = sum
 6         innerLst = [root.val]
 7         ansLst = []
 8         d.append((root, innerLst))
 9         while (len(d)):
10             nodeInfo = d.pop(0)
11             node = nodeInfo[0]
12             innerLst = nodeInfo[1]
13             if not node.left and not node.right:
14                 #print ("innerLst: ", innerLst, s, type(innerLst))
15                 #sumPath = sum(innerLst)
16                 sumPath = 0
17                 for e in innerLst:
18                     sumPath+=e
19                 if sumPath == s:
20                     ansLst.append(innerLst)
21             if node.left:
22                 d.append((node.left, innerLst + [node.left.val]))
23             if node.right:
24                 d.append((node.right, innerLst + [node.right.val]))
25         return ansLst

 

 

 

 

 
posted @ 2017-07-29 21:29  安新  阅读(223)  评论(0编辑  收藏  举报