码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树中和为某一值的路径

时间:2015-08-28 23:14:18      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:

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

注意find中最后要pop_back()。

 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         vector<vector<int>> res;
14         if(root==NULL)
15             return res;
16         vector<int> path;
17         find(root,expectNumber,res,path);
18         return res;
19     }
20 private:
21     void find(TreeNode* root,int expectNumber,vector<vector<int>> &res,vector<int> &path){
22         expectNumber-=root->val;
23         path.push_back(root->val);
24         if(expectNumber==0&&root->left==NULL&&root->right==NULL)
25             res.push_back(path);
26         if(root->left!=NULL)
27             find(root->left,expectNumber,res,path);
28         if(root->right!=NULL)
29             find(root->right,expectNumber,res,path);
30         path.pop_back();
31     }
32 };

 

二叉树中和为某一值的路径

标签:

原文地址:http://www.cnblogs.com/zl1991/p/4768067.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!