二叉树的创建采用递归创建
方案一:利用指针函数
include <iostream>
#include <stdlib.h>
using namespace std;
typedef struct BiNode
{
char data;
BiNode *lchild,*rchild;
}BiNode,*BiTree;
BiTree CreatBiTree()//先序遍历创建二叉树,定义指针函数
{
BiTree T;
char ch;
cin>>ch;
if(ch=='#')
T=NULL;
else
{
T=(BiTree)malloc(sizeof(BiNode));
T->data=ch;
T->lchild=CreatBiTree();//创建左子树
T->rchild=CreatBiTree();//创建右子树
}
return T;//返回根节点的指针
}
int main()
{
BiTree T;
T=CreatBiTree();
return 0;
}
方案二:void 函数+引用
#include <iostream>
#include <stdlib.h>
using namespace std;
typedef struct BiNode
{
char data;
BiNode *lchild,*rchild;
}BiNode,*BiTree;
void CreatBiTree(BiTree &T)//先序遍历创建二叉树&T为C++的引用
{
char ch;
cin>>ch;
if(ch=='#')
T=NULL;
else
{
T=(BiTree)malloc(sizeof(BiNode));
T->data=ch;
CreatBiTree(T->lchild);//创建左子树
CreatBiTree(T->rchild);//创建右子树
}
}
int main()
{
BiTree T;
CreatBiTree(T);
return 0;
}
两种创建方式各有优势