Advertisement
Guest User

Untitled

a guest
Mar 24th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.57 KB | None | 0 0
  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. bool hasPathSum(TreeNode* root, int sum) {
  13. // 树的 DFS 算法的终止条件通常需要考虑:空结点和叶结点
  14. if(root == nullptr) return sum == 0;
  15. if(!root->left && !root->right)
  16. return root->val == sum;
  17. return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
  18. }
  19. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement