题目:
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
链接:
剑指Offer(第2版):P182
思路标签:
- 举例子分析
- 算法:递归
- 数据结构:栈(用vector实现的栈功能)
解答:
1. C++
- 因为是从根结点开始访问形成路径,所以首先访问根结点,这就需要使用先序遍历的方式对树进行遍历;
- 访问到某一节点则将该节点添加到路径上,若该节点为叶节点,且路径累计和恰好为目标值,则该路径符合,添加到总路径集合中。
- 当前节点访问结束后,递归函数自动返回到父节点值,在退出前需在当前路径上删除当前节点;
- 不难看出是一个栈的形式来保存路径的,但是在得到路径后我们需要同时或得路径的所有节点值,所以使用vector来实现栈的功能。
/*
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) {
std::vector<vector<int>> allPath;
if(root == nullptr)
return allPath;
std::vector<int> path;
int currentSum = 0;
findAllPath(root, expectNumber, path, currentSum, allPath);
return allPath;
}
void findAllPath(TreeNode* root, const int expectNumber, vector<int> &path, int currentSum, vector<vector<int>> &allPath){
currentSum += root->val;
path.push_back(root->val);
//如果是叶节点且满足目标值则保存路径
bool isLeaf = root->left == nullptr && root->right == nullptr;
if(currentSum == expectNumber && isLeaf){
allPath.push_back(path);
}
//如果不是叶节点则继续访问子结点
if(root->left)
allPath = findAllPath(root->left, expectNumber, path, currentSum, allPath);
if(root->right)
allPath = findAllPath(root->right, expectNumber, path, currentSum, allPath);
path.pop_back();
return allPath;
}
};