I
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 andsum = 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.
刚开始想用回溯算法,但是后来发现有负数的情况下这种方法不行,所以就不能用回溯算法了,直接用简单粗暴的递归算法。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool judge(TreeNode *root, int sum,int flag) { if(root==NULL) return false; if(root->left==NULL&&root->right==NULL) return sum==root->val+flag; return judge(root->left,sum,flag+root->val)||judge(root->right,sum,flag+root->val); } bool hasPathSum(TreeNode *root, int sum) { return judge(root,sum,0); } };
Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22
,
5 / 4 8 / / 11 13 4 / / 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
/** * 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 { private: vector<vector<int>> res; vector<int> tempres; public: void subSum(TreeNode* root,int tempSum,int Sum) { if(root==NULL) return ; else if((tempSum+root->val==Sum)&&(root->left==NULL&&root->right==NULL)) { tempres.push_back(root->val); res.push_back(tempres); } else { tempres.push_back(root->val); subSum(root->left,tempSum+root->val,Sum); subSum(root->right,tempSum+root->val,Sum); } tempres.pop_back(); return; } vector<vector<int>> pathSum(TreeNode* root, int sum) { if(root==NULL) return res; else { subSum(root,0,sum); return res; } } };