二叉树 建树后DFS输出符合路径
最主要坑在建树。。。费了些神 还是不够
代码
#include
using namespace std;
typedef struct Node Node;
typedef struct Node *Nd;
typedef struct Node
{
int data;
Nd r,l;
}Node;
int d,tp,f;
int num[5555];
bool SetTree(Nd *t)
{
(*t) = (Nd)malloc(sizeof(Node));
char ch;
int x = 0,f = 0;
ch = getchar();
while(ch == ‘\n‘ || ch == ‘\r‘) ch = getchar();
while(ch >= ‘0‘ && ch <= ‘9‘)
{
f = 1;
x = x*10+ch-‘0‘;
ch = getchar();
}
if(f)
{
(*t)->data = x;
}
else (*t) = NULL;
// cout<<tp<<" "<<x<<endl;
if(ch == ‘(‘)
{
tp++;
if(SetTree(&((*t)->l))) getchar();
if(SetTree(&((*t)->r))) getchar();
tp--;
return 1;
}
else
{
if(f)
{
(*t)->l = NULL;
(*t)->r = NULL;
}
return 0;
}
}
void Dfs(int sum,Nd t)
{
//cout<<sum<<endl;
int i;
if(t->l == NULL && t->r == NULL && sum == d)
{
f = 1;
for(i = 0; i < tp;++i)
{
if(i) printf(" ");
printf("%d",num[i]);
}
printf("\n");
}else if(sum > d) return;
if(t->l)
{
num[tp++] = t->l->data;
Dfs(sum+num[tp-1],t->l);
tp--;
}
if(t->r)
{
num[tp++] = t->r->data;
Dfs(sum+num[tp-1],t->r);
tp--;
}
}
int main()
{
//freopen("in.txt","r",stdin);
int t,z = 0;
scanf("%d",&t);
char ch;
while(t--)
{
d = 0;
Nd tr;
SetTree(&tr);
ch = getchar();
tp = 0;
while(ch == ‘\n‘) ch = getchar();
while(ch != ‘\n‘ && ch != ‘\r‘)
{
d = d*10+ch-‘0‘;
ch = getchar();
}
tp = f = 0;
printf("Case %d:\n",++z);
num[tp++] = tr->data;
Dfs(num[0],tr);
if(!f) printf("I am so sorry!\n");
}
return 0;
}
时间: 2024-10-12 20:51:41