Path Sum

本文探讨了如何确定一棵二叉树中是否存在从根节点到叶子节点的路径,使得路径上所有节点值之和等于给定的目标值。通过递归算法实现深度优先搜索,检查每个可能的路径。

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

1st iteration:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum) {
        
        // invalid input
        if (root == NULL) {
            return false;
        }
        
        // leaf node
        if (root->left == NULL && root->right == NULL) {
            return root->val == sum;
        } 
        
        // depth-first-search
    
        // check on left child if it is not NULL
        if (root->left != NULL && hasPathSum(root->left, sum-root->val)) {
            return true;
        }
        
        // check on right child if it is not NULL
        if (root->right != NULL && hasPathSum(root->right, sum-root->val)) {
            return true;
        }
        
        return false;
    }
};


2nd iteration

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum) {
       return hasPathSumR(root, 0, sum);
    }
    
    // traverse the tree dfs, add up sum when traversing, when
    // approach leaft, compare with target sum, if equal return
    // otherwise, give up the path
    bool hasPathSumR(TreeNode *root, int sumSoFar, int target) {
        if (root == NULL) {
            return false;
        }
        
        // add up sum when traversing
        sumSoFar += root->val;
        
        // when approach leaft, compare with target sum,  if equal return
        // otherwise, give up the path
        if (root->left == NULL && root->right == NULL) {
            return sumSoFar == target;
        }
        
        // traverse the tree dfs
        return hasPathSumR(root->left, sumSoFar, target) ||
               hasPathSumR(root->right, sumSoFar, target);
    }
};



基于可靠性评估序贯蒙特卡洛模拟法的配电网可靠性评估研究(Matlab代码实现)内容概要:本文围绕“基于可靠性评估序贯蒙特卡洛模拟法的配电网可靠性评估研究”,介绍了利用Matlab代码实现配电网可靠性的仿真分析方法。重点采用序贯蒙特卡洛模拟法对配电网进行长时间段的状态抽样与统计,通过模拟系统元件的故障与修复过程,评估配电网的关键可靠性指标,如系统停电频率、停电持续时间、负荷点可靠性等。该方法能够有效处理复杂网络结构与设备时序特性,提升评估精度,适用于含分布式电源、电动汽车等新型负荷接入的现代配电网。文中提供了完整的Matlab实现代码与案例分析,便于复现和扩展应用。; 适合人群:具备电力系统基础知识和Matlab编程能力的高校研究生、科研人员及电力行业技术人员,尤其适合从事配电网规划、运行与可靠性分析相关工作的人员; 使用场景及目标:①掌握序贯蒙特卡洛模拟法在电力系统可靠性评估中的基本原理与实现流程;②学习如何通过Matlab构建配电网仿真模型并进行状态转移模拟;③应用于含新能源接入的复杂配电网可靠性定量评估与优化设计; 阅读建议:建议结合文中提供的Matlab代码逐段调试运行,理解状态抽样、故障判断、修复逻辑及指标统计的具体实现方式,同时可扩展至不同网络结构或加入更多不确定性因素进行深化研究。
### 三级标题:优化路径和查找代码以提高可读性与可维护性 为了提高代码的可读性和可维护性,可以对原有的路径和查找函数进行重构。主要优化点包括: 1. **函数职责分离**:将路径和计算与递归遍历逻辑分离。 2. **使用清晰的变量命名**:例如将 `currentSum` 改为 `currentPathSum`,增强语义表达。 3. **增加注释说明**:对关键步骤进行详细解释,提高代码可读性。 4. **避免全局变量**:使用指针参数传递计数器,避免全局状态。 以下是优化后的代码示例: ```c #include <stdio.h> #include <stdlib.h> typedef struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; } TreeNode; // 递归遍历路径和函数 void traversePaths(TreeNode* node, long currentPathSum, int targetSum, int* count) { if (node == NULL) { return; } currentPathSum += node->val; if (currentPathSum == targetSum) { (*count)++; } traversePaths(node->left, currentPathSum, targetSum, count); traversePaths(node->right, currentPathSum, targetSum, count); } // 主函数,计算路径和等于目标值的路径数目 int pathSum(TreeNode* root, int targetSum) { int count = 0; traversePaths(root, 0, targetSum, &count); return count; } ``` 该实现通过将路径和计算与递归遍历逻辑分离,提高了代码的模块化程度[^1]。此外,使用清晰的变量命名和注释,使得代码更易于理解和维护。 ### 三级标题:测试代码与内存释放 为了验证函数的正确性,可以编写测试代码,并在使用后释放内存以避免内存泄漏: ```c void testPathSum() { // 构建测试二叉树 TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode)); root->val = 10; root->left = (TreeNode*)malloc(sizeof(TreeNode)); root->left->val = 5; root->left->left = (TreeNode*)malloc(sizeof(TreeNode)); root->left->left->val = 3; root->left->left->left = NULL; root->left->left->right = NULL; root->left->right = (TreeNode*)malloc(sizeof(TreeNode)); root->left->right->val = 2; root->left->right->left = NULL; root->left->right->right = (TreeNode*)malloc(sizeof(TreeNode)); root->left->right->right->val = 1; root->left->right->right->left = NULL; root->left->right->right->right = NULL; root->right = (TreeNode*)malloc(sizeof(TreeNode)); root->right->val = -3; root->right->left = NULL; root->right->right = (TreeNode*)malloc(sizeof(TreeNode)); root->right->right->val = 7; root->right->right->left = NULL; root->right->right->right = NULL; int targetSum = 8; int result = pathSum(root, targetSum); printf("路径和等于 %d 的路径数目为: %d\n", targetSum, result); } // 释放二叉树节点内存 void freeTree(TreeNode* root) { if (root == NULL) { return; } freeTree(root->left); freeTree(root->right); free(root); } int main() { testPathSum(); return 0; } ``` 此测试代码通过构建一个具体的二叉树结构,并调用 `pathSum` 函数来验证其功能。最后,使用 `freeTree` 函数释放所有分配的内存资源,防止内存泄漏。 ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值