题目描述
递归和非递归
C++ 代码
blablabla
/**
* 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>> findPath(TreeNode* root, int sum) {
vector<vector<int>> res;
vector<int> path;
if(!root) return res;
//dfs(res,path,root,sum);
res = dfs(root,sum);
return res;
}
//递归
void dfs(vector<vector<int>> &res,vector<int>& path,TreeNode* r,int es){
if(r) path.push_back(r->val);
if(!r->left && !r->right){
if(es == r->val) res.push_back(path);
}
if(r->left) dfs(res,path,r->left,es - r->val);
if(r->right) dfs(res,path,r->right,es - r->val);
path.pop_back();
}
//非递归
vector<vector<int>> dfs(TreeNode* r,int sum){
vector<vector<int>> res;
vector<int> path;
stack<TreeNode*> st;
TreeNode* node = r;
while(node || st.size()){
while(node){
st.push(node);
path.push_back(node->val);
sum -= node->val;
node = node->left ? node->left : node->right;
}
node = st.top();
if(sum == 0 && !node->left && !node->right) res.push_back(path);
st.pop();
path.pop_back();
sum += node->val;
if(st.size() && st.top()->left == node) node = st.top()->right;
else node = nullptr;
}
return res;
}
};