标签:自己 sum include private nod 计算 www pat clu
https://leetcode-cn.com/problems/path-sum/
// 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;
}
};
// 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/
欢迎讨论和交流!
标签:自己 sum include private nod 计算 www pat clu
原文地址:https://www.cnblogs.com/chouxianyu/p/13377753.html