LeetCode112路径总和

题目链接

https://leetcode-cn.com/problems/path-sum/

题解一

  • 我自己写的
  • 在dfs过程中要记录当前节点与根节点之间的距离,并且回溯时也需要更新该值
  • 注意要求是叶子节点到根节点之间的距离
  • 详细思路见代码注释
// Problem: LeetCode 112
// URL: https://leetcode-cn.com/problems/path-sum/
// Tags: Tree Recursion DFS 回溯
// Difficulty: Easy

#include <iostream>
using namespace std;

struct TreeNode{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

class Solution{
private:
    bool existed = false;  // 当前是否存在叶子节点到根节点的路径和等于给定sum
    int now = 0;  // 当前节点的路径和
    int sum = -1;  // 给定的sum

    void dfs(TreeNode* root){
        // 如果当前已找到符合要求的节点,则不用再搜索
        if(existed==true)
            return ;
        // 如果是空节点,则不用搜索
        if(root==nullptr)
            return ;
        // 遍历当前节点,计算其到根节点之间的距离
        this->now += root->val;
        // 如果是叶子结点并且其与根节点的距离等于给定sum,则该节点符合条件
        if(root->left==nullptr && root->right==nullptr && this->now == this->sum){
            existed = true;
            return;
        }
        // 搜索左子树和右子树
        dfs(root->left);
        dfs(root->right);
        // 该子树已搜索完毕,需要更新当前节点与根节点之间的距离(回溯)
        this->now -= root->val;
    }

public:
    bool hasPathSum(TreeNode* root, int sum) {
        // 设置目标
        this->sum = sum;
        // 深度搜索
        dfs(root);
        // 返回搜索结果
        return this->existed;
    }
};

题解二

  • 别人的题解,用另外一种方式理解了sum,厉害 thumb up
// Problem: LeetCode 112
// URL: https://leetcode-cn.com/problems/path-sum/
// Tags: Tree Recursion DFS 回溯
// Difficulty: Easy

#include <iostream>
using namespace std;

struct TreeNode{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

class Solution{
public:
    bool hasPathSum(TreeNode* root, int sum) {
        if(root==nullptr)
            return false;
        if(root->left==nullptr && root->right==nullptr && root->val==sum)
            return true;
        return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);
    }
};

作者:@臭咸鱼

转载请注明出处:https://www.cnblogs.com/chouxianyu/

欢迎讨论和交流!


猜你喜欢

转载自www.cnblogs.com/chouxianyu/p/13377753.html