34 二叉树中和为某一值的路径
题目描述
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义
为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思路分析
这个题目也是很经典的,但是我今天太困了,,,,状态不好
反反复复做了好几遍才ac
清醒了,再重新看一看吧
代码
/*
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) {
if (root == NULL) return {};
vector<vector<int> > ret;
vector<int> path;
help(root, expectNumber, 0, path, ret);
return ret;
}
void help(TreeNode* p, int ep, int cur, vector<int> path, vector<vector<int> >& ret) {
cur += p->val;
path.push_back(p->val);
if (p->left == NULL && p->right == NULL) {
if (cur == ep) {
vector<int> tmp(path.begin(), path.end());
ret.push_back(tmp);
}
}
if (p->left) {
help(p->left, ep, cur, path, ret);
}
if (p->right) {
help(p->right, ep, cur, path, ret);
}
path.pop_back();
}
};