题目描述
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.
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.
题目思路
- 思路一、深度优先搜索,逐次向下递归查找,累加值。
值得注意的是此路径需要为根节点到叶子节点,所以需要判断是最后一个节点是叶子节点啊
其次需要注意代码中的 target,注意这不是引用,每个递归向下是累加此节点的数值的。但是向上返回时是没有计算此节点的。
/**
* 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 == NULL){
return false;
}
return core(root, sum, 0);
}
bool core(TreeNode* temp, int sum, int target){
target += temp->val;
int flag = false;
// 找到路径,则直接 flag=true,则不管左右子树为不为空,下面两个 if 都不会进去的
if(temp->left==NULL && temp->right==NULL && target==sum){
flag = true;
}
// 左子树不为空,且没找到路径(flag==false),则从此节点向下递归查找
if(flag == false && temp->left!=NULL){
flag = core(temp->left, sum, target);
}
// 右子树不为空,且没找到路径(flag==false),则从此节点向下递归查找
if(flag == false && temp->right!=NULL){
flag = core(temp->right, sum, target);
}
return flag;
}
};

网友评论