【二叉树】根据序列建树

已知先序序列和中序序列建树:

#include <iostream>
#include <cstring>
using namespace std;

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

//最好先在稿纸上写出a0...ak,ak+1...an-1的序列,找到左右子树的起点和终点 
void Create(BTNode *&T, char *pre, char *in, int n)	//n为该树的结点数 (思想为分治) 
{
	if(n <= 0)		//该树结点为0,空树 
	{
		T = NULL;
		return;
	}
	else
	{
		T = new BTNode;	//pre数组第一个元素就是根结点 
		T->data = *pre;
		int k; 	//k为该树根结点在中序(in)中的位置,用于给先序序列划分左右子树
		for(int i = 0;i < n;i++)	//在in中寻找根结点位置 
		{
			if(*pre == *(in+i))
			{
				k = i;
				break;
			}
		}
		
		Create(T->lchild, pre+1, in, k);	//该树的左子树对应的先序序列以pre+1为根结点,中序序列从in开始,有k个结点。
		Create(T->rchild, pre+k+1, in+k+1, n-k-1);	//该树的右子树对应的先序序列以pre+k+1为根结点,中序序列从p+1开始,含n-k-1个结点。 
		
	}
} 

void Pre(BTNode *T)
{
	if(T == NULL) return;	
	Pre(T->lchild);
	Pre(T->rchild);
	cout<<T->data;
}

int main()
{
	BTNode *T;
	char pre[20], in[20];
	cin>>pre>>in;
	//ABDGCEF
	//DGBAECF 
	Create(T, pre, in, strlen(pre));
	Pre(T);
	return 0;
}

已知后序序列和中序序列建树:

//DGBAECF
//GDBEFCA
#include <iostream>
#include <cstring>
using namespace std;

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

void Create(BTNode *&T, char *pos, char *in, int n)
{
	if(n <= 0)
	{
		T = NULL;
		return;
	}
	else
	{
		T = new BTNode;
		T->data = *(pos+n-1);
		int k;
		for(int i = 0;i < n;i++)
		{
			if(*(pos+n-1) == *(in+i))
			{
				k = i;
				break;
			}
		}
		Create(T->lchild, pos, in, k);
		Create(T->rchild, pos+k, in+k+1, n-k-1);
	}
} 

void Pre(BTNode *T)
{
	if(T)
	{
		cout<<T->data;
		Pre(T->lchild);
		Pre(T->rchild);
	}
}

int main()
{
	BTNode *T;
	char pos[20], in[20];
	cin>>pos>>in;
	Create(T, pos, in, strlen(pos));
	Pre(T);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Skyed_blue/article/details/89303216
今日推荐