面试题25 二叉树中和为某一值的路径

题目描述

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
 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){
14             return v;
15         }
16         
17         sum += root->val;
18         vc.push_back(root->val);
19         if (!root->left && !root->right && sum == expectNumber){
20             v.push_back(vc);
21         }
22         
23         if (root->left){
24             FindPath(root->left, expectNumber);
25         }
26         if (root->right){
27             FindPath(root->right, expectNumber);
28         }
29         
30         vc.pop_back();
31         sum -= root->val;
32         return v;
33     }
34 private:
35     vector<vector<int> > v;
36     vector<int> vc;
37     int i = 0, sum = 0;
38 };
原文地址:https://www.cnblogs.com/wanderingzj/p/5354470.html