//题目描述
//
//输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
#include<windows.h>
#include<vector>
#include<iostream>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
void dfs(TreeNode*root,int s,vector<int>&res,int expectNumber,vector<vector<int>>&vec){
s+=root->val;
res.push_back(root->val);
if(root->left==NULL&&root->right==NULL){
if(s==expectNumber){
vec.push_back(vector<int>(res));
}
res.pop_back();
return ;
}
if(root->left!=NULL)dfs(root->left,s,res,expectNumber,vec);
if(root->right!=NULL)dfs(root->right,s,res,expectNumber,vec);
res.pop_back();
}
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vector<vector<int>>vec;
vector<int>res;
if(root==NULL)return vec;
dfs(root,0,res,expectNumber,vec);
return vec;
}
};
int main(){
TreeNode*root=&TreeNode(10);
TreeNode*p=root;
p->left=&TreeNode(5);
p->right=&TreeNode(12);
p=p->left;
p->left=&TreeNode(4);
p->right=&TreeNode(7);
Solution test=Solution();
vector<vector<int>>res=test.FindPath(root,22);
cout<<res.size();
/*for(int i=0;i<res.size();i++){
for(int j=0;j<res[i].size();j++)
cout<<res[i][j]<<" ";
cout<<endl;
}*/
system("pause");
return 0;
}
【剑指offer】4.3举例让抽象问题具体化——面试题25:二叉树中和为某一值的路径
最新推荐文章于 2023-03-22 20:32:32 发布