- 题目描述
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
- 递归解法
class Solution {
public:
vector<vector<int>> ret;
vector<int> t;
vector<vector<int> > FindPath(TreeNode* root, int expectNumber) {
TreeNode* p = root;
stack<int> s;
if (root != NULL)
dfs(root, expectNumber);
return ret;
}
void dfs(TreeNode* root, int e){
t.push_back(root->val);
if (root->left == NULL && root->right == NULL && e-root->val==0)
ret.push_back(t);
else{
if (root->left)
dfs(root->left, e-root->val);
if (root->right)
dfs(root->right, e-root->val);
}
t.pop_back();
}
};
- 非递归解法
这个非递归还真是有点不太好写。。
class Solution {
public:
vector<vector<int>> res;
vector<vector<int> > FindPath(TreeNode* root, int expectNumber) {
TreeNode* p = root;
if (root == NULL)
return res;
stack<TreeNode*> s;
s.push(root);
int sum = 0;//当前和
vector<int> curPath;
TreeNode *cur = root;
TreeNode *last = NULL;
while (!s.empty()){
if (cur == NULL){
TreeNode* t = s.top();
if (t->right != NULL && t->right != last)
cur = t->right;//转向未遍历过的右子树
else{
last = t;//保存上一个已遍历地结点
s.pop();
curPath.pop_back();//从当前路径删除
sum -= t->val;
}
}
else{
s.push(cur);
sum += cur->val;
curPath.push_back(cur->val);
if (cur->left == NULL&&cur->right == NULL&&sum == expectNumber)
res.push_back(curPath);
cur = cur->left;//先序遍历,左子树先于右子树
}
}
return res;
}
};