欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-03-25 13:42:02
...

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.

相关标签: s