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

// 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);
	}
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值