1,题目要求
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:
给定一颗二叉树,是否存在一条从根节点到叶子节点的路径,使得路径上面的所有节点的和更与sum。
如果存在,返回true,否则,返回false。
2,题目思路
虽然有想法,也想到了迭代去做,但是实现起来还是很混乱。参考了一下discussion以后:
因为这样的一条路径是从根节点一直到叶子节点的,因此在进行路径寻找时,如果找到的对应的节点,也要看该节点是否为叶子节点。
在计算和的时候,还是利用差值来计算累加。也就是每次减去对应节点的值,来计算剩下的加和是否满足条件。这样做就省去了复杂的累加操作,beautiful。
3,程序源码
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root == NULL)
return false;
if(root->val == sum && root->left == NULL && root->right == NULL) //符合条件且为叶子节点
return true;
return hasPathSum(root->left, sum - (root->val)) || hasPathSum(root->right, sum - (root->val));
}
};