Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * 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) {
- // 树的 DFS 算法的终止条件通常需要考虑:空结点和叶结点
- if(root == nullptr) return sum == 0;
- if(!root->left && !root->right)
- return root->val == sum;
- return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement