Given a binary tree and a sum, determine if the tree has a root-to-leaf path such this adding up all the values along the Path equals the given sum.
For Example:
Given The below binary tree and
sum = 22,
5 / 4 8 / / / 4 / \ 7 2 1
Return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
/** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * Tre Enode (int x): Val (x), left (null), right (NULL) {} *}; */class Solution {public: bool Haspathsum (TreeNode *root, int sum) { return haspathsum (root,sum,0); } bool Haspathsum (TreeNode *root, int sum, int now) { if (root = NULL) return false; if (Root->left = = NULL && Root->right = = NULL && now+root->val = = sum) return true; bool L = haspathsum (root->left,sum,now+root->val); BOOL R = haspathsum (root->right,sum,now+root->val); return l| | R; }};
Leetcode--path Sum