您的位置:首页 > 其它

[leetcode]Path Sum II

2015-03-17 15:15 423 查看
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

DFS,当搜索到叶子节点时把路径存储下来。

/**
* 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 ans = false;
vector<int> st;
vector<vector<int>> v;
vector<vector<int> > pathSum(TreeNode *root, int sum) {
if(root == NULL) return v;
st.push_back(root->val);
if(root->left == NULL && root->right == NULL){
int a = 0;
for(int i=0;i<st.size();i++){
a += st[i];
}
ans = (a==sum);
if(ans){
vector<int> ve;
for(int i=0;i<st.size();i++){
ve.push_back(st[i]);
}
v.push_back(ve);
}
return v;
}
pathSum(root->left,sum);
if(root->left != NULL) st.erase(st.end()-1);
pathSum(root->right,sum);
if(root->right != NULL) st.erase(st.end()-1);
return v;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: