#include <iostream>
#include <queue>
// queue是C++语言中的头文件,它包含了队列的实现以及一系列的操作。
// 在这里是为了实现二叉树的层次实现
using namespace std;
#define TRUE 1
#define FALSE 0
#define Elemtype char
typedef struct tNode{
Elemtype data;
struct tNode *leftchild, *rightchild;
}tNode, *biTree;
void initBiTree(biTree &T) {
T = NULL;
}
// 先序创建二叉树
void createBiTree(biTree &T) {
Elemtype e;
cin >> e;
if(e != '#') {
T = new tNode;
T->data = e;
createBiTree(T->leftchild);
createBiTree(T->rightchild);
}
else {
T = NULL;
}
}
// 销毁树
void destroyBiTree(biTree &T) {
if(T == NULL) return ;
else {
destroyBiTree(T->leftchild);
destroyBiTree(T->rightchild);
delete(T);
}
}
// 获得一个结点的左子树
bool getLeftChildBiTree(biTree T, biTree &leftChild) {
if(T == NULL) return false;
else {
initBiTree(leftChild);
leftChild = T->leftchild;
return true;
}
}
// 获得一个结点的右子树
bool getRightChildBiTree(biTree T, biTree &rightChild) {
if(T == NULL) return false;
else {
initBiTree(rightChild);
rightChild = T->rightchild;
return true;
}
}
// 先序输出二叉树
void pre_outputBiTree(biTree T) {
if(T == NULL) return ;
else {
cout << T->data << " ";
pre_outputBiTree(T->leftchild);
pre_outputBiTree(T->rightchild);
}
}
// 中序输出二叉树
void med_outputBiTree(biTree T) {
if(T == NULL) return ;
else {
med_outputBiTree(T->leftchild);
cout << T->data << " ";
med_outputBiTree(T->rightchild);
}
}
// 后序输出二叉树
void lat_outputBiTree(biTree T) {
if(T == NULL) return ;
else {
lat_outputBiTree(T->leftchild);
lat_outputBiTree(T->rightchild);
cout << T->data << " ";
}
}
// 层序输出二叉树
void seq_outputBiTree(biTree T) {
queue<biTree> queue;
tNode *p;
queue.push(T);
while(! queue.empty()) {
cout << queue.front()->data << " ";
if(queue.front()->leftchild != NULL)
queue.push(queue.front()->leftchild);
if(queue.front()->rightchild != NULL)
queue.push(queue.front()->rightchild);
p = queue.front();
queue.pop();
}
}
// 获得二叉树的深度
int getDepthBiTree(biTree T) {
if(T == NULL) return 0;
else {
int leftDepth = getDepthBiTree(T->leftchild) + 1;
int rightDepth = getDepthBiTree(T->rightchild) + 1;
return max(rightDepth, leftDepth);
}
}
int main() {
biTree T;
initBiTree(T);
createBiTree(T);
pre_outputBiTree(T);
cout << endl;
med_outputBiTree(T);
cout << endl;
lat_outputBiTree(T);
cout << endl;
// destroyBiTree(T);
// pre_outputBiTree(T);
seq_outputBiTree(T);
cout << endl;
int res = getDepthBiTree(T);
cout << res << endl;
return 0;
}
数据结构链式二叉树C语言
最新推荐文章于 2025-01-18 00:17:35 发布
220

被折叠的 条评论
为什么被折叠?



