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]
]
ÎÊÌâÃèÊö£º¸ø¶¨Ò»¸ö¶þ²æÊ÷ºÍÒ»¸öÊý£¬ÕÒµ½ÔÚÕâ¸ö¶þ²æÊ÷ÖдӸù½Úµãµ½Ò¶×ӽڵ㷾¶ºÍµÈÓÚÕâ¸öÊý×ÖµÄËùÓз¾¶¡£
Ç°Ãæ¶à´ÎÌáµ½£¬Óë¶þ²æÊ÷Ïà¹ØµÄÎÊÌ⣬¶à°ë¶¼¿ÉÒÔÓõݹ顣
¶ÔÓÚ±¾Ìâ¶øÑÔ£¬vector<vector<int> > pathSum£¨TreeNode *root, int sum£©º¯Êý·µ»ØÒÔrootΪ¸ùµÄ·¾¶ºÍµÈÓÚsumµÄËùÓз¾¶£¬ÄÇô¿ÉÒÔÕâôÏë
pathSum£¨root->left, sum-£¨root->val£©£©·µ»Ø×ó×ÓÊ÷ÖкÍΪsum-£¨root->val£©µÄËùÓз¾¶£¬
pathSum£¨root->right, sum-£¨root->val£©£©·µ»ØÓÒ×ÓÊ÷ÖкÍΪsum-£¨root->val£©µÄËùÓз¾¶£¬
ÄÇôpathSum£¨root, sum£©¿ÉÒÔͨ¹ý½«root->val¼ÓÈëµ½ÉÏÃæËùÓз¾¶ÖУ¬È»ºó½«×óÓÒ×ÓÊ÷µÄ·¾¶½øÐкϲ¢µÃµ½¡£
È»ºóÔÙÅжÏÁÙ½çÌõ¼þ¼´¿É¡£
class Solution {
public:
vector<vector<int> > pathSum£¨TreeNode *root, int sum£© {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if£¨root == NULL£©
return vector<vector<int> >£¨£©£»
if£¨root->left == NULL && root->right == NULL && root->val == sum£© {
vector<vector<int> > vec;
vector<int> ivec;
ivec.push_back£¨sum£©£»
vec.push_back£¨ivec£©£»
return vec;
}
vector<vector<int> > vec1 = pathSum£¨root->left, sum-£¨root->val£©£©£»
vector<vector<int> > vec2 = pathSum£¨root->right, sum-£¨root->val£©£©£»
for£¨vector<vector<int> >::iterator iter = vec1.begin£¨£©£»
iter != vec1.end£¨£©£» ++iter£© {
£¨*iter£©¡£insert£¨£¨*iter£©¡£begin£¨£©£¬ root->val£©£»
}
for£¨vector<vector<int> >::iterator iter = vec2.begin£¨£©£»
iter != vec2.end£¨£©£» ++iter£© {
£¨*iter£©¡£insert£¨£¨*iter£©¡£begin£¨£©£¬ root->val£©£»
vec1.push_back£¨*iter£©£»
}
return vec1;
}
};