歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 二叉樹建立與遍歷

二叉樹建立與遍歷

日期:2017/3/1 10:06:53   编辑:Linux編程

本算法主要是利用擴展先序遍歷法創建二叉樹,再用先序遍歷遍歷二叉樹,最後按照樹形輸出整個二叉樹:

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

typedef int DataType;

typedef struct Node {
DataType data;
struct Node *LChild;
struct Node *RChild;
}BiNode,*BiTree;

void CreateBiTree(BiTree *bt) //擴展先序遍歷法建造BiTree
{
char ch;
ch = getchar();
if ('.' == ch)
*bt = NULL;
else
{
*bt = (BiTree)malloc(sizeof(BiNode));
(*bt)->data = ch;
CreateBiTree(&((*bt)->LChild));
CreateBiTree(&((*bt)->RChild));
}
}//CreateBitTree

void Visit(char ch)
{
printf("%c ",ch);
}//Visit

void PreOrder(BiTree root)
{
if (NULL != root)
{
Visit(root->data);
PreOrder(root->LChild);
PreOrder(root->RChild);
}
} //PreOrder

void PrintTree(BiTree Boot,int nLayer)
{
int i;
if (NULL == Boot)
return;
PrintTree(Boot->RChild,nLayer+1);
for (i=0; i<nLayer; ++i)
{
printf(" ");
}
printf("%c\n",Boot->data);
PrintTree(Boot->LChild,nLayer+1);
} //PrintTree

int main()
{
BiTree T;
int layer = 0;
printf("以擴展先序遍歷序列輸入,其中.代表空子樹:\n");
CreateBiTree(&T);
printf("PreOrder:");
PreOrder(T);
printf("\n");
PrintTree(T,layer);
return 0;
} //main

實例結果:

Copyright © Linux教程網 All Rights Reserved