题目描述:
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.
这题的意思是要我们找到一条路径,是路径上的所有节点数的和等于sum,不存在就返回false,存在就返回true。
解题思路:
既然sum的值等于路径上所有节点的和,我们就可以把sum的值减去节点数,如果减到最后等于0返回true。
这种解法肯定要遍历到每一个分支末端,所以我选择用递归实现。这个递归程序最重要的一点是如何处理分支末端的情况,条件有两个:1是“末端”这个情况,2是sum减去节点数等于0(也就是sum==val)。满足这两个情况就可以返回true。
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool hasPathSum(TreeNode* root, int sum) { 13 if(!root) 14 return 0; 15 if(sum==root->val&&!root->left&&!root->right) 16 return 1; 17 return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val); 18 } 19 };