Question
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Difficulty:Medium
Category:Tree, Depth-First-Search
Analyze
So we use the template code for this Tree Question
.
There are four steps for this template:
- Boundary conditions.
- Deal with the root value.
- recursive call funciton
- compare ouput value
Solution
/**
* 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) {
if (!root) return false;
if (!root->left && !root->right) return root->val == sum;
bool l = hasPathSum(root->left, sum - root->val);
bool r = hasPathSum(root->right, sum - root->val);
return l || r;
}
};