leetcode 112. Path sums

Given a binary tree and a target sum, determine whether there is a path from the root node to the leaf node in the tree. The sum of all node values ​​on this path is equal to the target sum.

Explanation: A leaf node is a node that has no child nodes.

Example: 
Given the following binary tree, and the target sum  sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

Returns  truebecause there is a root-to-leaf path with a target sum of 22  5->4->11->2.

I am still not proficient in the use of recursion, and I did not think of using the recursive method.

When solving tree-related problems, keep recursive thinking in mind

 

1 class Solution {
2 public:
3     bool hasPathSum(TreeNode* root, int sum) {
4         if(root == NULL) return false;
5         if(root->val == sum && root->left == NULL && root->right == NULL) return true;
6         return hasPathSum(root->right, sum-root->val) || hasPathSum(root->left, sum-root->val);
7     }
8 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325015270&siteId=291194637