数据结构:创建二叉树、中序遍历二叉树、先序遍历二叉树、后序遍历二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/haimianjie2012/article/details/83414729

1.

// 2015_2_BTNode.cpp : Defines the entry point for the console application.
//

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

typedef struct node {
	char data;
	struct node *parent, *lchild, *rchild;
}BTNode;
//创建不带头结点的二叉树
BTNode* CreateTree()
{
	BTNode* T;
	char m_ch;
	cin>>m_ch;
	if ('#'==m_ch)
	{
		T=NULL;
	} 
	else
	{
		T=new BTNode;
		T->data=m_ch;
		T->lchild=CreateTree();
		T->rchild=CreateTree();
	}
	return T;
}
//创建带头结点的二叉树
BTNode* CreateTreeWithParent(BTNode* par)
{
	BTNode* T;
	char m_ch;
	cin>>m_ch;	
	if ('#'==m_ch)
	{
		T=NULL;
	} 
	else
	{
		T=new BTNode;
		T->data=m_ch;
		T->parent=par;
		T->lchild=CreateTreeWithParent(T);
		T->rchild=CreateTreeWithParent(T);
	}
	return T;
}

void PreTravel(BTNode* root)
{
	if (root!=NULL)
	{
		printf("%c",root->data);
	}
	if (root->lchild!=NULL)
	{
		PreTravel(root->lchild);
	}
	if (root->rchild!=NULL)
	{
		PreTravel(root->rchild);
	}
}

void MidTravel(BTNode* root)
{
	if (root->lchild!=NULL)
	{
		MidTravel(root->lchild);
	}
	if (root->data!=NULL)
	{
		printf("%c",root->data);
	}
	
	if (root->rchild!=NULL)
	{
		MidTravel(root->rchild);
	}
}

void PostTravel(BTNode* root)
{
	if (root->lchild!=NULL)
	{
		PostTravel(root->lchild);
	}
	if (root->rchild!=NULL)
	{
		PostTravel(root->rchild);
	}

	if (root->data!=NULL)
	{
		printf("%c",root->data);
	}

	
}
BTNode* CopyTree(BTNode* t)
{
	BTNode* bt;
	if (t==NULL)
	{
		bt=NULL;
	} 
	else
	{
		bt=(BTNode*)malloc(sizeof(BTNode));
		bt->data=t->data;
		bt->lchild=CopyTree(t->lchild);
		bt->rchild=CopyTree(t->rchild);
	}
	return bt;
}
int _tmain(int argc, _TCHAR* argv[])
{
	BTNode* root=CreateTreeWithParent(NULL);
	BTNode* bt=CopyTree(root);
	printf("\n输出:\n");
	printf("\n先序遍历:\n");
	PreTravel(root);
	PreTravel(bt);
	printf("\n中序遍历:\n");
	MidTravel(root); 
	MidTravel(bt); 
	printf("\n后序遍历:\n");
	PostTravel(root);
	PostTravel(bt);
	int a=0;
	return 0;
}

2.

猜你喜欢

转载自blog.csdn.net/haimianjie2012/article/details/83414729
今日推荐