1. 程式人生 > >二叉樹的基本操作

二叉樹的基本操作

二叉樹作為一個應用廣泛的資料結構,是程式設計師必須掌握的結構之一。

在此記錄之前學習時寫出的實現及操作,以備不時之需。

目錄

測試程式碼

標頭檔案及二叉樹結構體

#include<stdio.h>
#include<malloc.h>
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
typedef struct bt
{
	char data;
	struct bt *lchild,*rchild;
}bt,*bitree;

二叉樹的建立

int create(bitree &t)
{
	char ch;
	scanf("%c",&ch);
	if(ch==' ') t=NULL;
	else
	{
		if(!(t=(bitree)malloc(sizeof(bt)))) return 0;
		t->data=ch;
		create(t->lchild);
		create(t->rchild);
	}
	return 1;
}

先序、中序、後序遍歷二叉樹(遞迴)

void pot(bitree &t)     /*先序遍歷二叉樹*/
{
	if(t) printf("%c ",t->data);
	if(t->lchild) pot(t->lchild);
	if(t->rchild) pot(t->rchild);
}

void iot(bitree &t)     /*中序遍歷二叉樹*/
{
	if(t)
	{
		if(t->lchild) iot(t->lchild);
		printf("%c ",t->data);
		if(t->rchild) iot(t->rchild);
	}
}

void lot(bitree &t)     /*後序遍歷二叉樹*/
{
 if(t)
 { if(t->lchild)
 lot(t->lchild);
 if(t->rchild)
 lot(t->rchild);
 printf("%c ",t->data);
 }
}

層序遍歷(非遞迴)

void cot(bitree &t)    /*層序遍歷二叉樹*/
{
	if(t)
	{queue<bitree>q;
	q.push(t);
	while(!q.empty())
	{
		bitree p=q.front();
		q.pop();
		printf("%c ",p->data);
		if(p->lchild) q.push(p->lchild);
		if(p->rchild) q.push(p->rchild);
	}
	}
}

先序、中序、後序遍歷二叉樹(非遞迴)


void fpot(bitree &t)
{
	if(!t)
	return ;
    stack<bitree>s;
    s.push(t);
    while(!s.empty())
	{
	bitree p=s.top();
	printf("%c ",p->data);
	s.pop();
	if(p->rchild) s.push(p->rchild );
	if(p->lchild) s.push(p->lchild );
	}
}

void fiot(bitree &t)
{
	stack<bitree>s;
	bitree p=t;
	while(p||!s.empty())
	{
		if(p)
		{
			s.push(p);
			p=p->lchild;
		}
		else
		{
			p=s.top();
			printf("%c ",p->data);
			s.pop();
			p=p->rchild ;
		}
	}
}

void flot(bitree &t)
{
	stack<bitree>s;
	bitree p=NULL,flag;
	s.push(t);
	while(!s.empty())
	{
		flag=s.top();
		if((flag->lchild==NULL&&flag->rchild==NULL)||(p!=NULL&&(p==flag->lchild||p==flag->rchild)))
		{
			s.pop();
			printf("%c ",flag->data);
			p=flag;
		}
		else
		{
			if(flag->rchild) s.push(flag->rchild);
            if(flag->lchild) s.push(flag->lchild);
		}
	}
}

測試程式碼

void main()
{
	bitree t;
	create(t);

	printf("遞迴:\n");
	printf("前序:");pot(t);printf("\n");
	printf("中序:");iot(t);printf("\n");
	printf("後序:");lot(t);printf("\n");


	printf("非遞迴:\n");
	printf("層序:");cot(t);printf("\n");
    printf("前序:");fpot(t);printf("\n");
	printf("中序:");fiot(t);printf("\n");
	printf("後序:");flot(t);printf("\n");

}

程式碼改變生活。