先序遍历建树及其输出(C和C++的不同)

破碎山河 破碎山河 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

#include "stdio.h"
#include "malloc.h"
#include "stdlib.h"
#include "string.h"
#include <iostream>
using namespace std;

struct tree;
typedef struct tree *Tree;

struct tree
{
char data;
Tree left;
Tree Right;
};

void CreatTree(Tree T)
{
char ch;
cin>>ch;
if(ch=='#')
return;
else
{
T=(Tree)malloc(sizeof(struct tree));
T->data=ch;
T->left=T->Right=NULL;
CreatTree(T->left);
CreatTree(T->Right);
}
}

void Print(Tree T)
{
while(T!=NULL)
{
printf("%c",T->data);
Print(T->left);
Print(T->Right);
}
}

int main()
{
Tree T=NULL;
CreatTree(T);
Print(T);
return 0;
}


这是我自己写的C版本、


#include<iostream>
using namespace std;
struct tree
{
char a;
tree *lchild,*rchild;
};
void set(tree *&b)
{
char ch;
cin>>ch;
if(ch=='#') return;
else
{
b=new tree;
b->a=ch;
b->lchild=b->rchild=NULL;
set(b->lchild);
set(b->rchild);
}
}
void print(tree *b)
{
if(b!=NULL)
{
cout<<b->a;
print(b->lchild);
print(b->rchild);
}
}
int main()
{
tree *b=NULL;
set(b);
print(b);
return 0;
}


这是朋友写的C++版本,

可以看出来在这两段函数上不同,我现在不知道怎么样修改,才能让指针传递符合要求?(即用C实现,而非用C++)


void Print(Tree T)
{
while(T!=NULL)
{
printf("%c",T->data);
Print(T->left);
Print(T->Right);
}
}
void print(tree *b)
{
if(b!=NULL)
{
cout<<b->a;
print(b->lchild);
print(b->rchild);
}
}


另外,前面有段时间去住院了,所以没有及时结贴,不好意思!
...全文
评论 10
收藏 已收藏
分享
返回顶部
破碎山河
模式及实现 5,529 成员 4,167 内容