【树】【回溯】leetcode_112_路径总和
程序员文章站
2022-03-03 11:02:23
...
【树】【回溯】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 hasPathSum(TreeNode* root, int targetSum) {
if(root == nullptr) return false;
return traversal(root, targetSum-root->val);
}
bool traversal (TreeNode* cur, int count){
if (cur->left == nullptr && cur ->right == nullptr && count==0) return true;
if (cur->left == nullptr && cur ->right == nullptr && count!=0) return false;
if (cur->left != nullptr){
count = count - cur->left->val;
bool re = traversal(cur->left, count);
if (re) return true;
count += cur->left->val;
}
if (cur->right != nullptr){
count = count - cur->right->val;
bool re = traversal(cur->right, count);
if (re) return true;
count += cur->right->val;
}
return false;
}
};
上一篇: Win10电脑如何设置U盘为第一启动项
下一篇: #94 二叉树的中序遍历