LeetCode - 解题笔记 - 112 - Path Sum

这篇博客介绍了如何使用深度优先搜索(DFS)解决二叉树中是否存在一条路径,使得路径上的节点值之和等于给定的目标值。提供了C++和Python两种语言的解决方案,时间复杂度和空间复杂度均为O(N),其中N为树的节点数。在平均情况下,空间复杂度为O(logN),最坏情况为O(N)。
摘要由CSDN通过智能技术生成

Solution 1

作为后一个题的基础,应用在二叉树场景的DFS:不断向下探索,只在叶子节点判断是否链上节点的和为给定值。由于未限定树的结构,因此DFS的搜索顺序不会产生很大影响。

  • 时间复杂度: O ( N ) O(N) O(N),其中 N N N为树中的节点个数,搜索算法,所有的节点最多遍历一次
  • 空间复杂度: O ( N ) O(N) O(N),其中 N N N为树中的节点个数,受调用函数栈深度影响,平均情况为 O ( log ⁡ N ) O(\log N) O(logN),最坏情况为 O ( N ) O(N) O(N)
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        
        return this->check(root, targetSum);

    }
    
private:
    bool check(TreeNode* node, int sumNow) {
        if(node == nullptr) {
            return false; // 缺省情况
        }
        
        if (node->left == nullptr && node->right == nullptr) {
            return node->val == sumNow;
        }
        
        return this->check(node->left, sumNow - node->val) || this->check(node->right, sumNow - node->val);
    }
};

Solution 2

Solution 1的Python实现

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        
        def check(node: Optional[TreeNode], sumNow: int) -> bool:
            if node is None:
                return False
            
            if node.left is None and node.right is None:
                return sumNow == node.val
        
            return check(node.left, sumNow - node.val) or check(node.right, sumNow - node.val)
        
        return check(root, targetSum)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值