408之二叉树(一)
今天学习了二叉树的层次建树和深度优先遍历算法,现在将实现的代码分享如下:
1. 二叉树结构定义
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>// 二叉树节点定义
typedef char bielemtype;
typedef struct bitree
{bielemtype data; // 节点数据域struct bitree* lchild, * rchild; // 左右子节点指针
}bitree, * pbitree;// 辅助队列节点定义(用于层次建树)
typedef struct tag
{pbitree p; // 指向二叉树节点struct tag* next; // 队列下一个节点指针
}tag, * ptag;
2. 二叉树遍历实现
// 前序遍历:根->左->右
void preorder(pbitree tree)
{if (tree != NULL){printf("%c", tree->data); // 先访问根节点preorder(tree->lchild); // 递归遍历左子树preorder(tree->rchild); // 递归遍历右子树}
}// 中序遍历:左->根->右
void midorder(pbitree tree)
{if (tree != NULL){midorder(tree->lchild); // 递归遍历左子树printf("%c", tree->data); // 访问根节点midorder(tree->rchild); // 递归遍历右子树}
}// 后序遍历:左->右->根
void postorder(pbitree tree)
{if (tree != NULL){postorder(tree->lchild); // 递归遍历左子树postorder(tree->rchild); // 递归遍历右子树printf("%c", tree->data); // 最后访问根节点}
}
3. 二叉树层次建树实现
// 二叉树层次建树主函数
int main()
{pbitree pnew; // 新创建的二叉树节点bielemtype c; // 读取的输入字符pbitree tree = NULL; // 二叉树根节点// 辅助队列指针(用于层次建树)ptag head = NULL, tail = NULL; // 队列头尾指针ptag pcur = NULL; // 当前处理的队列节点ptag list_pnew = NULL; // 新创建的队列节点while (scanf("%c", &c)) // 循环读取输入字符{if (c == '\n') // 遇到换行符结束输入{break;}// 创建新二叉树节点pnew = (pbitree)calloc(1, sizeof(bitree));pnew->data = c;// 创建对应的队列节点list_pnew = (ptag)calloc(1, sizeof(tag));list_pnew->p = pnew;// 处理第一个节点(根节点)if (tree == NULL){tree = pnew; // 设置根节点head = list_pnew; // 初始化队列tail = list_pnew;pcur = list_pnew;continue;}else{tail->next = list_pnew; // 新节点加入队列尾部tail = list_pnew;}// 将新节点挂载到当前处理的父节点if (pcur->p->lchild == NULL){pcur->p->lchild = pnew; // 挂载到左子树}else if (pcur->p->rchild == NULL){pcur->p->rchild = pnew; // 挂载到右子树pcur = pcur->next; // 当前父节点已满,移动到队列下一个节点}}// 输出三种遍历结果preorder(tree);printf("\n");midorder(tree);printf("\n");postorder(tree);return 0;
}