avatar

剑指Offer-二叉树中和为某一值的路径

📝题目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。

示例:

给定如下二叉树,以及目标和 target = 22,

5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1

返回:

[
[5,4,11,2],
[5,8,4,5]
]


📝思路

模拟一下路径可以明显看出与树的先序遍历有关。递归地访问树的节点直至到达叶子节点,维护一个计数器来判断当前路径和是否满足target,每次访问完叶子节点后都要降当前节点从路径中删去以返回上一节点。

📝题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
vector<vector<int>> pathSum(TreeNode* root, int target) {
vector<vector<int>> res;
vector<int> path;
int currentSum = 0;
findPath(root, target, currentSum, path, res);
return res;
}

void findPath(TreeNode* root, const int target, int& currentSum, vector<int>& path, vector<vector<int>>& res) {
if (!root) return;
currentSum += root->val;
path.push_back(root->val);

if (currentSum == target && !root->left && !root->right) {
res.push_back(path);
}

if (root->left) findPath(root->left, target, currentSum, path, res);
if (root->right) findPath(root->right, target, currentSum, path, res);

currentSum -= root->val;
path.pop_back();
}
Author:WhiteBeerHouse
Link:https://github.com/WhiteBeerHouse/WhiteBeerHouse.github.io/tree/master/2021/03/12/%E5%89%91%E6%8C%87Offer-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%AD%E5%92%8C%E4%B8%BA%E6%9F%90%E4%B8%80%E5%80%BC%E7%9A%84%E8%B7%AF%E5%BE%84/
Copyright Notice:All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.