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

数据结构之二叉树的递归创建、递归遍历

2013-03-23 13:02 525 查看
// Tree.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "stdio.h"
#include "iostream"

using namespace std;

typedef struct node
{
int data;
struct node *lchild;
struct node *rchild;
}BiTNode, *BiTree;

int CreateBiTree(BiTree &T);
int CreateBiTree(BiTree &T,int &index);
void PreOrder(BiTree root);
void InOrder(BiTree root);
void PostOrder(BiTree root);

int element[]={3,7,3,2,1,0,0,7,0,0,0,8,0,10,0,0,17,18,0,0,19,0,27,0,0};
static int index=0;
int _tmain(int argc, _TCHAR* argv[])
{

BiTree tree;
// 递归的创建二叉树
CreateBiTree(tree,index);
printf("创建二叉树完毕\n");
printf("先序遍历\n");
PreOrder(tree);
printf("\n");
printf("中序遍历二叉树\n");
InOrder(tree);
printf("\n");
printf("二叉树的后序遍历\n");
PostOrder(tree);
printf("\n");

system("pause");
return 0;
}

// 按照先序顺序,递归的创建二叉树
int CreateBiTree(BiTree &T)
{
int data;
scanf("%d",&data);
if (data==0) // 0代表子节点为空
{
T=NULL;
}
else
{
T=(BiTree)malloc(sizeof(BiTNode));
if (!T)
{
return -1;
}
else
{
T->data=data;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
return 1;
}

// 按照先序顺序,递归的创建二叉树,通过数组输入二叉树中的数据
int CreateBiTree(BiTree &T,int &index)
{
int data=element[index];
if (data==0) // 0代表子节点为空
{
T=NULL;
}
else
{
T=(BiTree)malloc(sizeof(BiTNode));
if (!T)
{
return -1;
}
else
{
T->data=data;
CreateBiTree(T->lchild,++index);
CreateBiTree(T->rchild,++index);
}
}
return 1;
}

// 先序遍历二叉树
void PreOrder(BiTree root)
{
if (root!=NULL)
{
printf("%3d",root->data);
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}

// 中序遍历
void InOrder(BiTree root)
{
if (root!=NULL)
{
InOrder(root->lchild);
printf("%3d",root->data);
InOrder(root->rchild);
}
}

// 后序遍历
void PostOrder(BiTree root)
{
if (root!=NULL)
{
PostOrder(root->lchild);
PostOrder(root->rchild);
printf("%3d",root->data);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: