0
final_list = []
def rec(node,node_list):
   node_list.append(node.val)
   if node.left == None and node.right == None:
      if sum(node_list)==total:
         final_list.append(node_list)
         print(node_list)
      del node_list[-1]
      return
   if node.left!=None:
      rec(node.left,node_list)
   if node.right!=None:
      rec(node.right,node_list)
   del node_list[-1]
node_list = []
rec(root,node_list)
print(final_list)

OUTPUT -

[5, 4, 11, 2]

[5, 8, 4, 5]

[[], []]

Why is final_list giving two blank lists as output?

The code above is for Path Sum II question of leetcode.

VaibhavSka
  • 25
  • 1
  • 7
  • Found the solution, use deepcopy from copy module during appending to final_list, to see detailed solution, visit, https://stackoverflow.com/questions/42885694/python-list-variable-not-storing-proper-result-in-recursion – VaibhavSka Oct 06 '20 at 18:06

1 Answers1

0
  • This problem relates to a Linked List not a regular Python list, then sum(node_list) does not work.

  • We'd first want to collect those self.val:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
  • Here is a working solution using a Depth First Search algorithm:
class Solution:
    def pathSum(self, root, target):
        if not root:
            return []
        
        def depth_first_search(node, target, path, res):
            if not (node.left or node.right) and target == node.val:
                path.append(node.val)
                res.append(path)

            if node.left:
                depth_first_search(node.left, target - node.val, path + [node.val], res)

            if node.right:
                depth_first_search(node.right, target - node.val, path + [node.val], res)

        nodes = []
        depth_first_search(root, target, [], nodes)
        return nodes
Emma
  • 27,428
  • 11
  • 44
  • 69