您的位置:首页 > 理论基础 > 数据结构算法

【数据结构】扩充先序遍历创建二叉树

2016-12-14 16:57 387 查看
   之前接触和学习的大多是二叉树的应用,即:二叉树的遍历、查找和排序等等。今天小编要介绍的是二叉树的创建。
   为了在程序中更有效和直观的创建一棵二叉树,可以使用,扩充先序遍历,来创建二叉树。
【定义】
   扩充先序遍历,首先要根据一棵二叉树写出它的先序遍历序列,然后根据二叉树中各个节点左右孩子的状况进行遍历,即:凡是没有左右孩子的节点,遍历到它的左右孩子时都用“.”来表示它的左右孩子,只是表示左右孩子,不算是节点,(当然也可以用*等其他任何自定义符号),最终结果是每个节点都有左右孩子,并且每个叶子节点都是自定义的.或者*。
【代码】(C语言版)

#include<stdio.h>
#include<stdlib.h>

typedef struct BinNode{//初始化
char element;
struct BinNode *left;
struct BinNode *right;
}BinNode,*BinTree;

void CreateBinTree(BinTree *tree){//根据所有序列创建二叉树
char ch;
scanf("%c",&ch);

if(ch == '*'){
(*tree) = NULL;
}
else{
if(!(*tree = (BinTree)malloc(sizeof(BinNode)))){
exit(-1);
}
(*tree)->element = ch;
CreateBinTree(&((*tree)->left));
CreateBinTree(&((*tree)->right));
}
}

void Preorder(BinTree T){//先序遍历
if(T){
printf("%c",T->element);
Preorder(T->left);
Preorder(T->right);
}
}

void Inorder(BinTree T){//中序遍历
if(T){
Inorder(T->left);
printf("%c",T->element);
Inorder(T->right);
}
}

void Postorder(BinTree T){//后序遍历
if(T){
Postorder(T->left);
Postorder(T->right);
printf("%c",T->element);
}
}

int main(){
BinTree T = NULL;

printf("请输入您要建立的二叉树的先序扩展序列(用*表示空)\n");
CreateBinTree(&T);
printf("构造二叉树成功!\n");
printf("先序遍历:");
Preorder(T);
printf("\n中序遍历:");
Inorder(T);
printf("\n后序遍历:");
Postorder(T);
printf("\n");
}
运行效果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: