Description
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.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
Explain
這道題一看就是深度優(yōu)先搜索的問(wèn)題了。題意很簡(jiǎn)單,就是從找一個(gè)條路钾怔,從根部到葉子显歧,其中節(jié)點(diǎn)的值加起來(lái)等于給定的值。那就遍歷每個(gè)節(jié)點(diǎn)幼东,每次到達(dá)一個(gè)新的葉子節(jié)點(diǎn)時(shí)臂容,加上當(dāng)前結(jié)點(diǎn)的值,看是否等于給定的值根蟹,如果是脓杉,那么就找到了。如果不是简逮,退回上一層繼續(xù)遍歷球散,直到遍歷完整個(gè)樹(shù),如果還找不到散庶,那就無(wú)解蕉堰。
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) {
bool flag = false;
if (!root) return false;
dfs(flag, root, sum, 0);
return flag;
}
void dfs(bool& flag, TreeNode* root, int sum, int _sum) {
if (flag) return;
if (root) {
dfs(flag, root->left, sum,_sum + root->val);
dfs(flag, root->right, sum,_sum + root->val);
_sum += root->val;
if(!root->left&&!root->right&&_sum == sum) flag = true;
}
}
};