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

题目描述:

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


分析:

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

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

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


深度优先搜索代码:

 1 /*
 2 struct TreeNode {
 3     int val;
 4     struct TreeNode *left;
 5     struct TreeNode *right;
 6     TreeNode(int x) :
 7             val(x), left(NULL), right(NULL) {
 8     }
 9 };*/
10 class Solution {
11 public:
12     vector<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     }
18     void 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:
29     vector<vector<int> > paths;
30 };
原文地址:https://www.cnblogs.com/jacen789/p/7747639.html