tree structure definition
typedef struct BiNode
{
char data;
struct BiNode *lchild, *rchild; //左右孩子指针
} BiTNode, *BiTree;
full code
#include<iostream>
#include <malloc.h>
using namespace std;
typedef struct BiNode
{
char data;
struct BiNode *lchild, *rchild; //左右孩子指针
} BiTNode, *BiTree;
//二叉树的创建
CreateBiTree(BiTree &T)
{
/*按先序次序输入二叉树中结点的值(一个字符),'#'字符表示空树
构造二叉链表表示的二叉树T*/
char ch;
cin >> ch;
if(ch=='#')
{
T=NULL;
}
else
{
T = (BiTree)malloc(sizeof(BiTNode));
T->data=ch; //生成根结点
CreateBiTree(T->lchild); //构造左子树
CreateBiTree(T->rchild);//构造右子树
}
};
//前序遍历二叉树
void PreOrder(BiTree T)
{
if(T)
{
cout << T->data;
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
//中序遍历二叉树
void InOrder(BiTree T)
{
if(T)
{
InOrder(T->lchild);
cout << T->data;
InOrder(T->rchild);
}
}
//后序遍历二叉树
void PostOrder(BiTree T)
{
if(T)
{
PostOrder(T->lchild);
PostOrder(T->rchild);
cout << T->data;
}
}
int main()
{
BiTree T = NULL;
CreateBiTree(T);
cout << "前序遍历结果 :";
PreOrder(T);
cout << "\n中序遍历结果 :";
InOrder(T);
cout << "\n前序遍历结果 :";
PostOrder(T);
}
operation result:
If there are any mistakes, criticisms and corrections are welcome.
Reference article: https://blog.csdn.net/qq_34941153/article/details/90316570