任务
1、实现二叉树的创建,存储结构为二叉链表结点类型
2、创建后实现先序中序后序的遍历结果
定义二叉树类和遍历时所需的栈
二叉树类:一个 char 变量用来放数据,两个指针变量用来放左右孩子地址
#include <iostream>
using namespace std;
class node {//定义二叉树类
public:
char data;
node* leftchild;
node* rightchild;
};
class stack {//定义栈
public:
char data;
stack* next;
};
定义压栈出栈函数
压栈函数传入栈顶地址和一个数据,出栈函数仅需传入栈顶地址
void push(stack*& stack1,char data) {//压栈
stack* top = NULL;
top = new stack;
top->data = data;
top->next = stack1;
stack1 = top;
}
void pop(stack*& stack1) {//出栈
cout << stack1->data;
stack1 = stack1->next;
}
定义创建二叉链表
判断正在创建的结点是否超出想要创建的二叉树的结点数,如果超出则断开,没有超出就将数据存入新结点。然后决定新结点应放在头结点的左孩子还是右孩子,本代码的方法是:如果左孩子为空,就放左孩子,否则放右孩子。然后递归循环,直到结点创建完毕。
void creat(node*head,char* a,int amount,int number) {//递归创建二叉表
node* node1 = NULL;
node1 = new node;
if (number > amount) {//如果正在创建的结点不属于给定的数据,则跳过此次调用
return;
}
node1->data = a[number-1];//储存数据进data
if (head->leftchild == NULL) {//如果leftchild有结点了,则将正在创建的结点的地址给rightchild,否则给leftchild
head->leftchild = node1;
}
else
{
head->rightchild = node1;
}
node1->leftchild = new node;
node1->rightchild = new node;
node1->leftchild = NULL;
node1->rightchild = NULL;
creat(node1, a,amount, 2 * number);//创建左孩子
creat(node1, a, amount,2 * number + 1);//创建右孩子
}
遍历函数
先序遍历
如果结点为空或储存的是 # 就跳过,否则直接输出数据,然后递归循环。
void first(node*head) {//先序遍历
if (head == NULL) {//如果为空则跳过,否则输出data
return;
}
if (head->data == '#') {//遇到#就跳过
return;
}
cout << head->data;//不用压栈直接在函数里就cout
first(head->leftchild);
first(head->rightchild);
}
中序遍历
先判断数据是否为 #,是就跳过,否则先将数据压栈,然后判断左孩子是否为空,如果不为空则递归循环,否则出栈(左孩子的值),再出栈(根节点的值),然后递归。
void second(node*head,stack*stack1) {//中序遍历
if (head->data == '#') {//遇到#就跳过
return;
}
push(stack1, head->data);//先压栈再判断孩子是否为空
if (head->leftchild != NULL) {//如果左孩子不为空则将左孩子递归调用,
second(head->leftchild, stack1);
}
else//否则出栈
{
pop(stack1);
return;
}
pop(stack1);//因为左孩子已遍历,所以再出一个栈(根结点)
second(head->rightchild, stack1);//最后遍历右孩子
}
后序遍历
void third(node* head, stack* stack1) {//后序遍历
if (head->data == '#') {//遇到#就跳过
return;
}
push(stack1, head->data);//先压栈再判断左右孩子是否为空
if (head->leftchild != NULL) {//第一判断左孩子是否为空
third(head->leftchild, stack1);
}
if (head->rightchild != NULL) {//第二判断右孩子是否为空
third(head->rightchild, stack1);
}
pop(stack1);//最后再出根结点
}
主函数
int main() {
char a[500]{}; node* head = NULL; int amount = 0;
head = new node; head->leftchild = NULL;
stack* stack = NULL;
cout << "请输入要储存的数组(结点为空写作#,数组结尾用?):" << endl;
for (int i = 0; i < 500; i++)
{
cin >> a[i];
amount++;
if (a[i] == '?' ) {
amount--;
break;
}
}
creat(head, a, amount,1);//创建二叉链表
head = head->leftchild;//因为使用层次创建法,二叉表真正的头结点是leftchild,在此转换
cout << "先序遍历结果为:";
first(head); cout << endl;
cout << "中序遍历结果为:";
second(head, stack); cout << endl;
cout << "后序遍历结果为:";
third(head, stack); cout << endl;
}