0%

二叉树中和为某一值的路径

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

深搜,找到则保存。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<int> path;
vector<vector<int>> result;
void DoFindPath(TreeNode* root,int expectNumber)
{
if (root == nullptr)
{
if (expectNumber == 0 && path.size() > 0)
{
result.push_back(path);
}
}
else
{
path.push_back(root->val);
if (root->left == nullptr)
{
if (root->right == nullptr)
{
if (root->val == expectNumber)
{
result.push_back(path);
}
}
else
{
FindPath(root->right, expectNumber - root->val);
}
}
else
{
FindPath(root->left, expectNumber - root->val);
if (root->right != nullptr)
{
FindPath(root->right, expectNumber - root->val);
}
}
path.pop_back();
}
}
vector<vector<int>> FindPath(TreeNode* root,int expectNumber)
{
DoFindPath(root, expectNumber);
return result;
}
};