数据结构 c++
二叉树的基本操作
建立一棵二叉树,试编程实现二叉树的如下基本操作:
1. 按先序序列构造一棵二叉链表表示的二叉树T;
2. 对这棵二叉树进行遍历:先序、中序、后序以及层次遍历,分别输出结点的遍历序列;
3. 求二叉树的深度/结点数目/叶结点数目;
4. 将二叉树每个结点的左右子树交换位置。
[主要实验代码步骤和结果]
定义二叉树树:
typedef struct BiTNode
{
char data;
struct BiTNode* lchild, * rchild;
};
创建二叉树(先序创建 递归):
BiTNode* CreateTree()//先序创建二叉树
{
BiTNode* T;
char x;
cin >> x;
if (x == '@')//‘@’表示子树为空。
T = NULL;
else
{
T = new BiTNode;
T->data = x;
cout << "输入左孩子:";
T->lchild = CreateTree();
cout << "输入右孩子:";
T->rchild = CreateTree();
}
return T;}
中序遍历二叉树(递归)
主要代码:
void InOrderDisplay(BiTNode* T)//中序遍历(递归)
{
if (T)
{InOrderDisplay(T->lchild);//中序遍历左子树(递归)
cout << T->data << setw(4);//访问根节点
InOrderDisplay(T->rchild);//右子树
}}
层次遍历(利用队链的入栈和出栈实现树的层次遍历)
主要代码:typedef struct QNode
{BiTNode *data;
struct QNode* next;
}QNode, * QueuePtr;
typedef struct LinkQueue
{QueuePtr front;
QueuePtr rear;
};
void InitQueue(LinkQueue& Q)//初始化栈链。
{Q.front = Q.rear = new QNode;
Q.front->next = NULL;
}
void EnQueue(LinkQueue& Q, BiTNode* e)//入栈。
{QNode* p = new QNode;
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
}
BiTNode *DeQueue(LinkQueue& Q, BiTNode *e)//出栈。
{if (Q.front == Q.rear)
return NULL;
QNode* p = new QNode;
p = Q.front->next;
e = p->data;
Q.front->next = p->next;
if (Q.rear == p)
Q.rear = Q.front;
delete p;return e;}//以上为队列的创建。
void LevelDisplay(BiTNode* T)//层序遍历
{BiTNode* t = new BiTNode;
BiTNode* e = new BiTNode;
LinkQueue Q;
InitQueue(Q);
EnQueue(Q, T);
while (t = DeQueue(Q, e))
{cout << t->data;
if (t->lchild != NULL)
{EnQueue(Q, t->lchild);}
if (t->rchild != NULL)
{EnQueue(Q, t->rchild);
}}}