题目描述:

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

分析:

先序遍历二叉树,找到二叉树中结点值的和为输入整数的路径,加入到路径数组中。

注意:路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。必须到达叶子结点。

这个问题是可以深度优先搜索,也可以广度优先搜索。

深度优先搜索代码:

 /*
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 paths;
vector<int> path;
MyFindPath(root, expectNumber, path);
return paths;
}
void MyFindPath(TreeNode* root, int expectNumber, vector<int> &path) { // 先序遍历
if(root == NULL) return;
path.push_back(root->val);
if(expectNumber == root->val && root->left == NULL && root->right == NULL) {
paths.push_back(path); // 存在expectNumber等于root->val,加入结果数组中
}
MyFindPath(root->left, expectNumber - root->val, path);
MyFindPath(root->right, expectNumber - root->val, path);
path.pop_back();
}
private:
vector<vector<int> > paths;
};
04-18 21:39