Leetcode 437. Path Sum III (python+cpp)

该博客探讨了LeetCode 437题目的解决方案,强调了路径可能不从根节点开始的难点。错误的初始想法是路径必须从根节点开始,而正确的解法则是采用递归策略,考虑树中每个节点作为路径起点的情况。博主提供了Python和C++两种语言的实现,并指出可以使用字典进行记忆化搜索以避免双重递归,但针对此题而言并不必要。

Leetcode 437. Path Sum III

题目

在这里插入图片描述

错误解法:

这道题目坑爹的地方在于路径可以不从根节点开始。刚看到题目的时候天真的以为是从根节点开始,于是就有了下面的错误解法:

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> int:
        self.count = 0
        def count_path(root,curr_sum):
            if not root:
                return
            if root.val+curr_sum == sum:
                self.count += 1
            count_path(root.left,root.val+curr_sum)
            count_path(root.right,root.val+curr_sum)
        
        count_path(root,0)
        return self.count

正确解法:

正确解法有点坑爹,需要递归套递归。因为可以不从根节点开始的话,就意味着你需要考虑以每个节点为路径开始节点的情况。具体如下:

  • 构造一个helper函数,这个helper函数的功能和上面错误解法的功能是一样的,在以当前节点作为路径第一个结点的情况下,计算有多少条符合条件的路径
  • 递归pathSum函数,分别传入当前root节点,以及当前root节点的左节点和右节点,用来穷尽以树中每一个节点为路径开始节点的情况。三者的和才是最后答案

python代码如下:

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> int:
        def count_path(root,curr_sum):
            if not root:
                return 0
            if curr_sum+root.val == sum:
                count = 1
            else:
                count = 0
            count+=count_path(root.left,curr_sum+root.val)
            count+=count_path(root.right,curr_sum+root.val)
            return count
        
        if not root:
            return 0
        return count_path(root,0)+self.pathSum(root.left,sum)+self.pathSum(root.right,sum)

C++代码如下:

class Solution {
public:
    int pathSum(TreeNode* root, int sum) {
        if (!root) return 0;
        return count_path(root,0,sum)+pathSum(root->left,sum)+pathSum(root->right,sum);
    }
    int count_path(TreeNode* root,int curr_sum,int sum){
        if (!root) return 0;
        int count = (curr_sum+root->val)==sum ? 1:0;
        count += count_path(root->left,curr_sum+root->val,sum);
        count += count_path(root->right,curr_sum+root->val,sum);
        return count;
    }
};

当然这道题目也可以加入字典来记忆,这样就不需要双重递归,但是我觉得为了这么一道普通的题目没必要

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值