剑指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> > path;
13     vector<int> p;
14     vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
15         if(root == NULL)
16             return path;
17         p.push_back(root->val);
18         if( (expectNumber - root->val == 0) && root->left == NULL && root->right == NULL )
19             path.push_back(p);
20         FindPath(root->left,expectNumber - root->val); 
21         FindPath(root->right,expectNumber - root->val);
22         //若左右结点均为空,则将进行回溯,将数组中已有的值删除。
23         if(p.size() != 0)
24             p.pop_back();
25         return path;
26     }
27 };

我的笔记:

  由于本题目的要求,需要对不满足条件的结点进行回溯,即可采用递归的方式。换言之,就是对整个二叉树进行遍历,每当找到满足条件的就将其数组 p 置入 path 中。

posted @ 2020-05-27 14:09  John_yan15  阅读(99)  评论(0编辑  收藏  举报