二叉树的创建和各种遍历方法

本文介绍了一种使用递归方法创建二叉树的方法,并实现了前序、中序及后序遍历。通过控制台输入先根遍历序列来构建二叉树,然后展示三种不同的遍历方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码如下:

// CreateBinaryTree1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

typedef struct node
{
	char data;
	struct node *lchild;
	struct node *rchild;
} treenode;

treenode* CreateBinTree()
{
	char x;
	cin>>x;
	treenode* temp;
	if ('$'==x)
	{
		temp=NULL;
	}
	else
	{
		temp = new treenode;
		temp->data = x;
		temp->lchild=CreateBinTree();
		temp->rchild=CreateBinTree();
	}
	return temp;
}
//前序遍历
void preorder(treenode* p)
{
	if(p!=NULL)
	{
		cout<<p->data<<" ";
		preorder(p->lchild);
		preorder(p->rchild);
	}
}
//中序遍历
void midorder(treenode* p)
{
	if(p!=NULL)
	{
		midorder(p->lchild);
		cout<<p->data<<" ";
		midorder(p->rchild);
	}
}

//后序遍历
void postorder(treenode* p )
{
	if(p!=NULL)
	{
		postorder(p->lchild);
		postorder(p->rchild);
		cout<<p->data<<" ";
	}
}


int _tmain(int argc, _TCHAR* argv[])
{
	cout<<"请以先根遍历输入一序列,$表示空:\n";
	treenode *root  = CreateBinTree();
	cout<<"前序遍历: ";
	preorder(root);
	cout<<endl;
	cout<<"中序遍历:";
	midorder(root);
	cout<<endl;
	cout<<"后序遍历:";
	postorder(root);
	cout<<endl;
	
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值