BinTree_T.c
#include <stdio.h>
#include <stdlib.h>
#define DataType char
typedef struct BinaryTree
{
DataType data;
struct BinaryTree *lchild, *rchild;
}BTNode, *BinTree;
void visit(DataType m)
{
printf("%c ",m);
}
//建立二叉树
BinTree CreatBinTree()
{
char ch;
BinTree T;
scanf(" %c",&ch);//注意前面有个空格
if(ch=='#')
T=NULL;
else
{
T=(BinTree)malloc(sizeof(BTNode));
if(!T)
exit(1);
T->data=ch;
T->lchild=CreatBinTree();
T->rchild=CreatBinTree();
}
return T;
}
//先序遍历
void Preorder(BinTree bt)
{
if(bt)
{
visit(bt->data);
Preorder (bt->lchild);
Preorder (bt->rchild);
}
}
//中序遍历
void Inorder (BinTree bt)
{
if(bt)
{
Inorder(bt->lchild);
visit(bt->data);
Inorder(bt->rchild);
}
}
//后序遍历
void Postorder (BinTree bt)
{
if(bt)
{
Postorder ( bt->lchild );
Postorder ( bt->rchild );
visit(bt->data);
}
}
int heigh(BinTree Q)
{
int lh,rh;
if(Q==NULL)
return 0;
lh=heigh(Q->lchild);
rh=heigh(Q->rchild);
return (lh>rh?lh:rh)+1;
}
int main()
{
BinTree root;
int h;
root=CreatBinTree();
printf("先序序列二叉树已经建立");
h=heigh(root);
printf("高度:%d\n",h);
Preorder(root);
return 0;
}
BinTree_T.cpp
#include <iostream>
using namespace std;
#define DataType char
typedef struct BinaryTree{
DataType data;
struct BinaryTree *lchild, *rchild;
}BTNode, *BinTree;
void visit(char m)
{
printf("%c ",m);
}
//建立二叉树
bool CreatBinTree(BinTree &T)
{
char ch;
scanf(" %c",&ch);//&&&注意%c前面有个空格
if(ch=='#')
T=NULL;
else
{
T=(BinTree)malloc(sizeof(BTNode));
if(!T)
return false;
T->data=ch;
CreatBinTree(T->lchild);
CreatBinTree(T->rchild);
}
return true;
}
//先序遍历
void Preorder(BinTree bt)
{
if(bt)
{
visit(bt->data);
Preorder (bt->lchild);
Preorder (bt->rchild);
}
}
//中序遍历
void Inorder (BinTree bt)
{
if(bt)
{
Inorder(bt->lchild);
visit(bt->data);
Inorder(bt->rchild);
}
}
//后序遍历
void Postorder (BinTree bt)
{
if(bt)
{
Postorder ( bt->lchild );
Postorder ( bt->rchild );
visit(bt->data);
}
}
int main()
{
BinTree root;
CreatBinTree(root);
Preorder(root);
return 0;
}