题目描述
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
题目分析
两种方法,递归的DFS和非递归的做法就是利用二叉树的后序遍历的非递归算法来做的,由于二叉树的后序遍历的非递归算法要借助辅助栈,当访问一个结点时,栈中的元素依次就是从根到达该结点的路径。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vector<vector<int> > ret;
vector<int> path;
dfs(ret,root,expectNumber,path,0,0);
return ret;
}
void dfs(vector<vector<int> > &ret,TreeNode* root,int expectNumber,vector<int> &path,int len,int sum){
if(root == nullptr)
return;
if(len == path.size())
path.push_back(root->val);
else
path[len]=root->val;
if(sum+root->val==expectNumber&&root->left==nullptr&&root->right==nullptr){
vector<int> arr(len+1);
for(int i=0;i<len+1;arr[i]=path[i],++i);
ret.push_back(arr);
return;
}
dfs(ret,root->left,expectNumber,path,len+1,sum+root->val);
dfs(ret,root->right,expectNumber,path,len+1,sum+root->val);
}
};
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vector<vector<int> > ret;
vector<pair<TreeNode*, int> > st;
TreeNode *p = root;
for (int sum = 0; p || !st.empty(); ) {
if (p) {
sum += p->val;
st.emplace_back(p, 1);
p = p->left;
} else {
auto now = st.back();
st.pop_back();
if (now.second == 1) {
st.emplace_back(now.first, 2);
p = now.first->right;
} else if (sum == expectNumber && now.first->left == nullptr && now.first->right == nullptr) {
vector<int> arr(st.size() + 1);
for (int i = 0; i < (int)st.size(); arr[i] = st[i].first->val, ++i);
ret.push_back((arr[st.size()] = now.first->val, arr));
sum -= now.first->val;
} else
sum -= now.first->val;
}
}
return ret;
}
};