【问题标题】:why is it returning a blank final_list?为什么它返回一个空白的final_list?
【发布时间】:2021-01-19 13:25:12
【问题描述】:
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问题。

【问题讨论】:

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


【解决方案1】:
  • 此问题与 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

【讨论】:

    猜你喜欢
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 2020-12-14
    相关资源
    最近更新 更多