剑指Offer第24题:二叉树中和为某一值的路径

题目:输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

解题思路:定义一个辅助函数,用于遍历二叉树,当遍历至叶子结点时,判断是否符合条件。注意:辅助函数中的res要用引用传递。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void FindPathHelper(vector<vector<int> > &res, vector<int> one_res, int sum, TreeNode* root, int n) {
if (root) { //根据二叉树的遍历修改代码
sum += root->val;
one_res.push_back(root->val);
if (sum == n && !root->left && !root->right) { //达到根结点并且当前的和与目标和相等
res.push_back(one_res);
one_res.clear();
sum = 0;
}
FindPathHelper(res, one_res, sum, root->left, n);
FindPathHelper(res, one_res, sum, root->right, n);
}
}
bool compare(vector<int> a, vector<int> b)
return a.size() > b.size();
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vector<vector<int> > res;
FindPathHelper(res, {}, 0, root, expectNumber);
sort(res.begin(), res.end(), compare); //数组长度大的数组靠前
return res;
}