为什么返回空白的final_list?

时间:2020-10-04 14:17:25

标签: python-3.x recursion binary-search-tree

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)

输出-

[5、4、11、2]

[5,8,4,5]

[[],[]]

为什么final_list给出两个空白列表作为输出?

上面的代码是针对leetcode的Path Sum II问题的。

1 个答案:

答案 0 :(得分:0)

  • 此问题与Linked List而不是常规Python list有关,然后sum(node_list)不起作用。

  • 我们首先要收集这些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
  • 这是使用深度优先搜索算法的可行解决方案:
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
相关问题