温馨提示:读者一定要了解二叉树的先序、中序、后续遍历方法才能继续往下看哦~~
一. 二叉树的储存结构
typedef struct node {
char date;
node* Lchild;//左子树
node* Rchild;//右子树
};
二. 二叉树的建立
先序遍历创建二叉树(递归)
node* CreatTree()
{
char ch;
node* T = new node;
cin >> ch;
if (ch == '*')
T = NULL;
else
{
T->date = ch;
T->Lchild = CreatTree();
T->Rchild = CreatTree();
}
return T;
}
三.总代码
因为输入要按照二叉树的性质来,就是说对于有n个节点的二叉树,就有n+1个空域,在这里即为如果你输入了n个元素,那么一定要有n+1个*才会结束递归过程
#include<iostream>
#include<stdio.h>
using namespace std;
typedef struct node {
char date;
node* Lchild;//左子树
node* Rchild;//右子树
};
node* CreatTree()
{
char ch;
node* T = new node;
cin >> ch;
if (ch == '*')
T = NULL;
else
{
T->date = ch;
T->Lchild = CreatTree();
T->Rchild = CreatTree();
}
return T;
}
//前序遍历
void Pre_Order(node* T)
{
if (T)//如果T存在的话
{
cout << T->date;
Pre_Order(T->Lchild);
Pre_Order(T->Rchild);
}
}
//中序遍历
void In_Order(node* T)
{
if (T)
{
In_Order(T->Lchild);
cout << T->date;
In_Order(T->Rchild);
}
}
//后序遍历
void Post_Order(node* T)
{
if (T)
{
Post_Order(T->Lchild);
Post_Order(T->Rchild);
cout << T->date;
}
}
int main()
{
node* T;
T = CreatTree();
cout << "先序遍历的输出:";
Pre_Order(T);
cout << endl;
cout << "中序遍历的输出";
In_Order(T);
cout << endl;
cout << "后序遍历的输出";
Post_Order(T);
system("pause");
}
输入:ABDH##I##E##CF#J##G##