您的位置:首页 > 其它

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

2016-04-05 22:09 309 查看

题目描述

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

/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<vector<int>>res;
void findpath(TreeNode* root,int val,int sum,vector<int>& path)
{
if(root==NULL)
return ;
sum+=root->val;
path.push_back(root->val);
bool isleaf=false;
if(root->left==NULL&&root->right==NULL)
isleaf=true;
if(sum==val&&isleaf)
res.push_back(path);
if(root->left)
findpath(root->left,val,sum,path);
if(root->right)
findpath(root->right,val,sum,path);
path.pop_back();

}
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if(root==NULL) return res;
vector<int> path;
int sum=0;
findpath(root,expectNumber,sum,path);
return res;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: