二叉树的创建与遍历

我们依然通过结构体来定义它的结点结构;分为数据域,指向左孩子的指针(指向左结构体),指向右孩子的指针(指向右结构体)

二叉树的结点结构

typedef char Type;//Type是自己定义的数据类型
//二叉链表存储结构
typedef struct TreeNode
{
	Type data;
	struct TreeNode* Lchild;
	struct TreeNode* Rchild;
}TreeNode;

创建一个二叉树

我们需要改变指针所指向的数据,并且递归会跳出函数,所以需要用二级指针;x数组是我们传入的数据,index在递归之前相当于一个全局变量,为了让它在每一次递归时都要自增,我们需要传入指针

void creatTree(TreeNode** T, Type* x, int* index)//因为要递归,所以需要二级指针
{
	Type ch;
	ch = x[*index];//将x数组的元素一个一个的赋给ch
	*index += 1;//索引自增
	if (ch == '#')//递归出口
	{
		*T = NULL;
	}
	else
	{
		*T = new TreeNode;
		(*T)->data = ch;//赋值
		creatTree(&((*T)->Lchild), x, index);//递归遍历创建左孩子
		creatTree(&((*T)->Rchild), x, index);//递归遍历创建右孩子	
	}
}

数据的访问

void visit(TreeNode* T)
{
	cout << T->data << " ";
}

前序遍历

void preOrder(TreeNode* T)//前序遍历
{
	if (T == NULL)
		return;
	else
	{
		visit(T);
		preOrder(T->Lchild);
		preOrder(T->Rchild);
	}
}

中序遍历

void inOrder(TreeNode* T)//中序遍历
{
	if (T == NULL)
		return;
	else
	{
		inOrder(T->Lchild);
		visit(T);
		inOrder(T->Rchild);
	}
}

后序遍历

void postOrder(TreeNode* T)//后续遍历
{
	if (T == NULL)
		return;
	else
	{
		postOrder(T->Lchild);
		postOrder(T->Rchild);
		visit(T);
	}
}

完整的二叉树创建与遍历

#include<iostream>
using namespace std;
typedef char Type;
//二叉链表存储结构
typedef struct TreeNode
{
	Type data;
	struct TreeNode* Lchild;
	struct TreeNode* Rchild;
}TreeNode;
void creatTree(TreeNode** T, Type* x, int* index)//因为要递归,所以需要二级指针
{
	Type ch;
	ch = x[*index];//将x数组的元素一个一个的赋给ch
	*index += 1;//索引自增
	if (ch == '#')//递归出口
	{
		*T = NULL;
	}
	else
	{
		*T = new TreeNode;
		(*T)->data = ch;//赋值
		creatTree(&((*T)->Lchild), x, index);//递归遍历创建左孩子
		creatTree(&((*T)->Rchild), x, index);//递归遍历创建右孩子	
	}
}
void visit(TreeNode* T)
{
	cout << T->data << " ";
}
void preOrder(TreeNode* T)//前序遍历
{
	if (T == NULL)
		return;
	else
	{
		visit(T);
		preOrder(T->Lchild);
		preOrder(T->Rchild);
	}
}
void inOrder(TreeNode* T)//中序遍历
{
	if (T == NULL)
		return;
	else
	{
		inOrder(T->Lchild);
		visit(T);
		inOrder(T->Rchild);
	}
}
void postOrder(TreeNode* T)//后续遍历
{
	if (T == NULL)
		return;
	else
	{
		postOrder(T->Lchild);
		postOrder(T->Rchild);
		visit(T);
	}
}

int main()
{
	TreeNode* T;
	int index = 0;
	Type x[16] = { 'A','B','D','#','#','E','#','#','C','F','#','#','G','#','#' };
	creatTree(&T, x, &index);
	cout << "前序遍历:";
	preOrder(T);
	cout << endl;
	cout << "中序遍历:";
	inOrder(T);
	cout << endl;
	cout << "后序遍历:";
	postOrder(T);
	cout << endl;
}

输入的#是来确定结点无孩子,比如ABC:

 

         

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值