问题描述:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note: A leaf is a node with no children.
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]
]
源码:
就是112题目的变种leetcode【112】Path Sum。递归的方法,时间还行,内存要爆了。本来想着tmp变量也用指针,最后想想不对,那不左子树得数据影响到右子树了。没办法了,只能老老实实用vector<int> tmp(不敢加&)。后来又看了看Disucuss区里面,每次弄完pop不就完了,空间时间都省了,时间94%,空间100%。
/**
* 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:
void help(vector<vector<int>> &result, vector<int> &tmp, TreeNode* root, int sum){
tmp.push_back(root->val);
if(root->val==sum && !root->left && !root->right){
result.push_back(tmp);
tmp.pop_back();
return;
}
if(root->left) help(result, tmp, root->left, sum - root->val);
if(root->right) help(result, tmp, root->right, sum - root->val);
tmp.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> result;
if(!root) return result;
vector<int> tmp;
help(result, tmp, root, sum);
return result;
}
};
非递归如果继续用112题的方式,可能需要多个队列,貌似中序遍历的方式会更好,虽然理解起来比122题麻烦,时间81%,空间100%(思路和第110题的非递归有点像leetcode【110】Balanced Binary Tree)
/**
* 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:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> result;
if(!root) return result;
vector<int> path;
stack<TreeNode*> st;
TreeNode *pre = NULL;
int cursum = 0;
while(root || !st.empty()){
while(root){
st.push(root);
cursum += root->val;
path.push_back(root->val);
root = root->left;
}
root = st.top();
if(root->right && root->right!=pre){
root = root->right;
}
else{
if(!root->left && !root->right && cursum==sum)
result.push_back(path);
st.pop();
pre = root;
path.pop_back();
cursum -= root->val;
root = NULL;
}
}
return result;
}
};