题目描述:
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
分析:
先序遍历二叉树,找到二叉树中结点值的和为输入整数的路径,加入到路径数组中。
注意:路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。必须到达叶子结点。
这个问题是可以深度优先搜索,也可以广度优先搜索。
深度优先搜索代码:
1 /* 2 struct TreeNode { 3int val; 4struct TreeNode *left; 5struct TreeNode *right; 6TreeNode(int x) : 7 val(x), left(NULL), right(NULL) { 8} 9 };*/10 class Solution {11 public:12vector<vector<int> > FindPath(TreeNode* root, int expectNumber) {13 if(root == NULL) return paths;14 vector<int> path;15 MyFindPath(root, expectNumber, path);16 return paths;17}18void MyFindPath(TreeNode* root, int expectNumber, vector<int> &path) { // 先序遍历19 if(root == NULL) return;20 path.push_back(root->val);21 if(expectNumber == root->val && root->left == NULL && root->right == NULL) {22 paths.push_back(path); // 存在expectNumber等于root->val,加入结果数组中23 }24 MyFindPath(root->left, expectNumber - root->val, path);25 MyFindPath(root->right, expectNumber - root->val, path);26 path.pop_back();27}28 private:29vector<vector<int> > paths;30 };
如果觉得《剑指Offer——二叉树中和为某一值的路径》对你有帮助,请点赞、收藏,并留下你的观点哦!