2023每日刷题(五十七)
Leetcode—112.路径总和
实现代码
/*** 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 dfs(TreeNode* root, int sum) {if(root == nullptr) {return false;}if(root->left == nullptr && root->right == nullptr) {return sum == root->val;}return dfs(root->left, sum - root->val) || dfs(root->right, sum - root->val);}bool hasPathSum(TreeNode* root, int targetSum) {return dfs(root, targetSum);}
};
算法思想
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!