首页 > 代码库 > Path Sum <leetcode>

Path Sum <leetcode>

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.

 

这道题也很简单,其实就是遍历(这里用的前序,用递归实现的),把每个节点求和,到叶子节点时看是不是满足条件,如果不满足继续遍历,都没有就返回false,

但是一开始理解错了,想当然的以为如果左右节点有一个NULL就算一条路径,真是低级的错误,左右子节点都是NULL时才算一条路径

代码如下:

 

 1 /** 2  * Definition for binary tree 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==NULL) return false;14         return doit(root,sum);15     }16     17     bool doit(TreeNode* &root,int sum)18     {
if
19 if(NULL==root->left&&NULL==root->right)20 {21 if(0==sum-root->val) return true;22 else return false;23 }24 else25 {26 if(NULL!=root->left)27 {28 if(!doit(root->left,sum-root->val))29 {30 if(NULL!=root->right)31 {32 return doit(root->right,sum-root->val);33 }34 else return false;35 }36 return true;37 }38 else if(NULL!=root->right)39 {40 return doit(root->right,sum-root->val);41 }42 }43 }44 };

 

Path Sum <leetcode>