二叉树结构
/*
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) {
map<TreeNode*, pair<int, vector<int>>> mm;
vector<vector<int> > paths;
stack<TreeNode*> S;
TreeNode *q, *p = root;
if(root == NULL) return paths;
mm[root] = make_pair(root->val, vector<int>(1, root->val));
while(p || !S.empty()){
if(p){
S.push(p);
q = p;
p = p->left;
if(p){
int sum = mm[q].first + p->val;
vector<int> path2(mm[q].second);
path2.push_back(p->val);
mm[p] = make_pair(sum, path2);
}
}
else {
q = S.top();
S.pop();
p = q->right;
if(p){
int sum = mm[q].first + p->val;
vector<int> path2(mm[q].second);
path2.push_back(p->val);
mm[p] = make_pair(sum, path2);
}
else{
// 叶结点
if(mm[q].first == expectNumber)
paths.push_back(mm[q].second);
}
}
}
// 字典序
sort(paths.begin(), paths.end());
return paths;
}
};
最标准的方法应该是后序遍历,因为遍历到叶节点时,栈中的元素刚好就是从根节点到叶结点的路径。
class Solution {
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
map<TreeNode*, pair<int, vector<int>>> mm;
vector<vector<int> > paths;
vector<int> path;
vector<TreeNode*> S;
TreeNode *r, *p = root;
int sum;
if(root == NULL) return paths;
while(p || !S.empty()){
if(p){
S.push_back(p);
p = p->left;
}
else{
p = S.back();
if(p->right != NULL && p->right != r){
p = p->right;
S.push_back(p);
p = p->left;
}
else{
if(p->right == NULL){
sum = 0;
path.clear();
for(int i = 0; i < S.size(); i++){
sum += S[i]->val;
path.push_back(S[i]->val);
}
if(sum == expectNumber){
paths.push_back(path);
}
}
S.pop_back();
r = p;
p = NULL;
}
}
}
sort(paths.begin(), paths.end());
return paths;
}
};