题目
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.
思路:DFS递归
可以将此问题转化为左右子树是否存在何为sum-root->val
的子情况。
这种问题bool函数一般分四步:
- 特殊情况为空为零的
- 返回值为true的终止情况
- 递归调用子函数的返回值判断情况
- 其余情况,返回值为false
四步处理中应保证第二步第四步都有返回。
/**
* 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==nullptr)//1.
return false;
int sub=sum-root->val;
if(sub==0 && root->left==nullptr && root->right==nullptr)//2.
return true;
if(hasPathSum(root->left,sub)||hasPathSum(root->right,sub))//3.
return true;
return false;//4.
}
};
网友评论