先序遍历建树及其输出(C和C++的不同)
#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);
}
}
另外,前面有段时间去住院了,所以没有及时结贴,不好意思!
...全文
相关推荐
C++先序遍历的顺序建立二叉链表
C++先序遍历的顺序建立二叉链表,
二叉树 C++实现 建树 前序 中序 后序 层序
我们实习的任务 做出来分享一下!!!二叉树 C++实现 建树 前序 中序 后序 层序
先序遍历的非递归算法
先序遍历的非递归算法C语言二叉树前序、中序、后序三种遍历的非递归算法和递归算法最精悍版
c实现二叉树先序层序遍历
要求能够输入树的各个结点,并能够输出用不同方法遍历的遍历序列; 分别建立建立二叉树存储结构的的输入函数、输出层序遍历序列的函数、输出先序遍历序列的函数
C语言用递归法求二叉树的最大宽度并层序遍历输出
C语言用递归法将二叉树层序遍历,并求出最大宽度。文件类型是.cpp的,c的编译器都可以编译。


模式及实现
