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: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.
1.我的解法(递归)
/**
* 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 pathsum(TreeNode* root, int all, int sum){
if(root->left== NULL && root->right == NULL){
if(all+root->val == sum)
return true;
else
return false;
}
if(root->left== NULL || root->right == NULL){//这里需要处理只有一个子节点的情况,不能把有空的那条算为路径
TreeNode* t = root->left!=NULL?root->left:root->right;
return pathsum(t,all+root->val,sum);
}else{
return pathsum(root->left,all+root->val,sum)||pathsum(root->right,all+root->val,sum);
}
}
bool hasPathSum(TreeNode* root, int sum) {
if(!root)
return false;
return pathsum(root,0,sum);
}
};上面做法是,如果碰到只有一个子节点,则将那个子节点传下去;
下面的做法是,如果碰到空了(只有一个子节点,则另一个子节点就是为空,),那么这个分叉不属于一条路径,则直接置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 pathsum(TreeNode* root, int all, int sum){
if(root==NULL)
return false;
if(root->left== NULL && root->right == NULL){
if(all+root->val == sum)
return true;
else
return false;
}
return pathsum(root->left,all+root->val,sum)||pathsum(root->right,all+root->val,sum);
}
bool hasPathSum(TreeNode* root, int sum) {
if(!root)
return false;
return pathsum(root,0,sum);
}
};
2.别人的解法(递归)
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);
}Path Sum 路径和(注:同时包含得到各个路径的模板:两种不同表达形式的代码)
原文:http://blog.csdn.net/u010005161/article/details/51330237