题目:
输入一个整数和一棵二叉树。打印出和与输入整数相等的所有路径。
路径指的是从树的根结点开始往下访问一直到叶结点的路径。
例子:
例如输入整数22和如下二叉树
10
/ \
5 12
/ \
4 7
则打印出两条路径:10, 12和10, 5, 7。
思路:
当访问到某一结点时,添加到路径上,并累加当前结点的值。
如果当前结点不是叶结点,则继续访问它的子结点。当前结点访问结束后,递归函数回到父结点。
访问完当前节点,返回时删除并减去当前结点的值,确保返回父结点时路径刚好是根到父结点的路径。
#include<iostream>
#include<vector>
using namespace std;
typedef struct Tree
{
struct Tree* l;
struct Tree* r;
int val;
}tree;
void path(tree* root,int num,int& cur,vector<int>& v)
{
if(root==NULL) return;
cur+=root->val;
v.push_back(root->val);
int leaf=0;
if((root->l==NULL) && (root->r==NULL)) leaf=1;
if((leaf==1) &&(cur==num))
{
for(auto iter:v)
{
cout<<iter<<" ";
}
cout<<endl;
}
if(root->l) path(root->l,num,cur,v);
if(root->r) path(root->r,num,cur,v);
cur-=root->val;
v.pop_back();
}
tree* creat_tree(int* a,int size,int& index)
{
tree* root=new tree;
if(index<size && a[index]=='#')
{
root=NULL;
}
if(index<size && a[index]!='#')
{
root->val=a[index];
root->l=creat_tree(a,size,++index);
root->r=creat_tree(a,size,++index);
}
return root;
}
int main()
{
/*
tree* root=new tree;
tree* p10=new tree;
tree* p11=new tree;
tree* p20=new tree;
tree* p21=new tree;
root->l=p10;
root->r=p11;
root->l->l=p20;
root->l->r=p21;
root->val=10;
p10->val=5;
p11->val=12;
p20->val=4;
p21->val=7;
p20->l=NULL;
p20->r=NULL;
p21->l=NULL;
p21->r=NULL;
p11->l=NULL;
p11->r=NULL;
*/
int a[11]={10,5,4,'#','#',7,'#','#',12,'#','#'};
int index=0;
tree* root=creat_tree(a,11,index);
int cur=0;
vector<int> v;
path(root,22,cur,v);
return 0;
}
'''
输出:
10 5 7
10 12
'''
剑指offer 二叉树中和为某一值的所有路径
最新推荐文章于 2021-04-20 20:45:51 发布