二叉树的遍历

温馨提示:读者一定要了解二叉树的先序、中序、后续遍历方法才能继续往下看哦~~

一. 二叉树的储存结构

typedef struct node {
	char date;
	node* Lchild;//左子树
	node* Rchild;//右子树
};

二. 二叉树的建立

先序遍历创建二叉树(递归)

node* CreatTree()
{
	char ch;
	node* T = new node;
	cin >> ch;
	if (ch == '*')
		T = NULL;
	else
	{
		T->date = ch;
		T->Lchild = CreatTree();
		T->Rchild = CreatTree();
	}
	return T;
}

三.总代码

因为输入要按照二叉树的性质来,就是说对于有n个节点的二叉树,就有n+1个空域,在这里即为如果你输入了n个元素,那么一定要有n+1个*才会结束递归过程


#include<iostream>
#include<stdio.h>
using namespace std;
typedef struct node {
	char date;
	node* Lchild;//左子树
	node* Rchild;//右子树
};
node* CreatTree()
{
	char ch;
	node* T = new node;
	cin >> ch;
	if (ch == '*')
		T = NULL;
	else
	{
		T->date = ch;
		T->Lchild = CreatTree();
		T->Rchild = CreatTree();
	}
	return T;
}
//前序遍历
void Pre_Order(node* T)
{
	if (T)//如果T存在的话
	{
		cout << T->date;
		Pre_Order(T->Lchild);
		Pre_Order(T->Rchild);
	}
}
//中序遍历
void In_Order(node* T)
{
	if (T)
	{
		In_Order(T->Lchild);
		cout << T->date;
		In_Order(T->Rchild);
	}
}
//后序遍历
void Post_Order(node* T)
{
	if (T)
	{
		Post_Order(T->Lchild);
		Post_Order(T->Rchild);
		cout << T->date;
	}
}
int main()
{
	node* T;
	T = CreatTree();
	cout << "先序遍历的输出:";
	Pre_Order(T);
	cout << endl;
	cout << "中序遍历的输出";
	In_Order(T);
	cout << endl;
	cout << "后序遍历的输出";
	Post_Order(T);
	system("pause");

}

输入:ABDH##I##E##CF#J##G##


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值