二叉树的创建与遍历

二叉树的遍历

思路:

二叉树的遍历主要是理解递归算法的思想,遍历的时候调用自己本身,直到自己本身成为根节点,然后输出自己,在返回上一个递归。
测试用例:
ABC##DE#G##F###

#include <iostream>
using namespace std;
typedef struct _BiTNode
{
	
	char data;
	struct _BiTNode *leftChild;
	struct _BiTNode *rightChild;
	
}BiTNode,*BiTree;
BiTree CreatBiTree()
{
	char ch;
	BiTree t;
	cin>>ch;
	if(ch=='#') t=NULL;
	else
	{
			
		t=(BiTree)malloc(sizeof(BiTNode));
		t->data=ch;
		t->leftChild=CreatBiTree();
		t->rightChild=CreatBiTree();
	}
	
	return t;
}


void PreOrder(BiTree t)
{
	
	if(t)
	{
		
		cout<<t->data<<" ";
		PreOrder(t->leftChild);
		PreOrder(t->rightChild);
	}
}

void InOrder(BiTree t)
{
	
	if(t)
	{
		
		InOrder(t->leftChild);
		cout<<t->data;
		InOrder(t->rightChild);
		
	}
}

void PostOrder(BiTree t)
{
	
	if(t)
	{
		PostOrder(t->leftChild);
		PostOrder(t->rightChild);
		cout<<t->data;
		
	}
}
int main(int argc, char *argv[])
{
	BiTree t;
	t=CreatBiTree();
	cout<<"二叉树创建"<<endl;
	cout<<"先序遍历"<<endl;
	PreOrder(t);
	cout<<endl;
	cout<<"中序遍历"<<endl;
	InOrder(t);
	cout<<endl;
	cout<<"后序遍历"<<endl;
	PostOrder(t);
	cout<<endl;
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值