1.先序创建二叉树,再遍历(前序、中序、后序、层序)
2.自由输入字符,空节点由“#”符号代替
3.求二叉树的高
4.找到树中所有叶子节点
5.叶子节点到根节点的路径
代码如下:
#include <stdio.h>
#include <malloc.h>
#define maxSize 100
/************二叉树一个结构体,数据是字符型********/
typedef struct BiNode {
char data;
struct node* lchild;
struct node* rchild;
}BiNode, *BinaryTree;
/*********前序创建二叉树*********/
CreateBiTree(BinaryTree *T)
{
char ch;
scanf_s("%c", &ch);
if ('#' == ch) //如果输入"#"号,表示这个结点为空
*T = NULL;
else
{
*T = (BiNode*)malloc(sizeof(BiNode));
(*T)->data = ch;
CreateBiTree(&(*T)->lchild);
CreateBiTree(&(*T)->rchild);
}
}
/***************前序遍历***********/
void preorder(BinaryTree T, int level)
{
if (T != NULL)
{
printf("%c--第%d层 ", T->data, level);
preorder(T->lchild, level + 1);
preorder(T->rchild, level + 1);
}
}
/**************中序遍历**************/
void inorder(BinaryTree T, int level)
{
if (T != NULL)
{
inorder(T->lchild, level + 1);
printf("%c--第%d层 ", T->data, level);
inorder(T->rchild, level + 1);
}
}
/**************后序遍历***************/
void postorder(BinaryTree T, int level)
{
if (T != NULL)
{
printf("%c--第%d层 ", T->data, level);
postorder(T->lchild, level + 1);
postorder(T->rchild, level + 1);
}
}
/*************层次遍历*************/
void levelorder(BinaryTree T)
{
if (T != NULL)
{
BinaryTree q[maxSize];
q[0] = T;
int front = 0;
int rear = 1;
while (front < rear)
{
printf("%c ", q[front]->data);
if (q[front]->lchild)
q[rear++] = q[front]->lchild;
if (q[front]->rchild)
q[rear++] = q[front]->rchild;
++front;
}
}
}
/***********求二叉树的高**********/
int get_height(BinaryTree T)
{
if (T == NULL)
return 0;
else
{
int left_height = get_height(T->lchild);
int right_height = get_height(T->rchild);
int max = left_height;
if (max < right_height)
max = right_height;
return max + 1;
}
}
/***************找到树中的叶子节点************/
void findLeaf(BinaryTree T)
{
if (T != NULL)
{
if (T->lchild == NULL && T->rchild == NULL)
printf("%c ", T->data);
findLeaf(T->lchild);
findLeaf(T->rchild);
}
}
/**************叶子节点到根节点的路径****************/
//当T是空节点,返回上层,不做处理
//当T是叶子节点,将T加入路径中
//当T不是叶子节点也不是空节点时,将该节点加入路径
void getLeafPath(BinaryTree T,char path[],int pathLength)
{
if (T != NULL)
{
if (T->lchild == NULL && T->rchild == NULL)
{
path[pathLength] = T->data;
printf("%c叶子节点到根节点的路径为: ", T->data);
for (int i = pathLength; i >= 0; i--)
{
printf("%c ",path[i]);
}
printf("\n");
}
else
{
path[pathLength++] = T->data;
getLeafPath(T->lchild, path, pathLength);
getLeafPath(T->rchild, path, pathLength);
pathLength--;
}
}
}
int main()
{
int level = 1;
BinaryTree T = NULL;
int pathLength = 0;
char path[maxSize];
printf("请输入结点:");
CreateBiTree(&T);
printf("\n前序遍历结果为:\n");
preorder(T, level);
printf("\n中序遍历结果为:\n");
inorder(T, level);
printf("\n后序遍历结果为:\n");
postorder(T, level);
int height = get_height(T);
printf("\n二叉树的高度为:%d", height);
printf("\n二叉树中的叶子节点为:");
findLeaf(T);
printf("\n");
getLeafPath(T, path, pathLength);
printf("\n");
printf("层序遍历结果为:");
levelorder(T);
system("pause");
}
构建这么一棵二叉树:
按照先序创建二叉树为:ABC##DE##F##GH#J##I##
结果如图所示: