I. Question
We will give you a binary tree and an integer to determine whether there is a path from the root node to the leaf node in the tree so that the value on this path is the sum of this integer.
Example: binary tree and value 22
5
/\
4 8
//\
11 13 4
/\\
7 2 1
Path: 5-4-11-+ 4 + 11 + 2 = 22
II. Analysis
First of all, what makes me feel the worst about this question?
1> value determination (PS: even if the root node is not 0, the result may be 0. Do not forget that the value can be negative or zero)
2> If sum = 0 and root node is NULL, the result is true or false. It turns out that if the root node is NULL, the result is false;
Next, we can continue to use recursion by using sum to subtract the value of the current left or right subtree and call this function again.
/*** Definition for binary tree * 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) {if (root = NULL) return false; if (root-> left = NULL & root-> right = NULL & sum = root-> val) return true; return hasPathSum (root-> left, sum-root-> val) | hasPathSum (root-> right, sum-root-> val );}};
Leetcode: Path_Sum