1. 程式人生 > >根據二叉樹的前序和中序或者後序和中序來確定二叉樹結構(附例題)

根據二叉樹的前序和中序或者後序和中序來確定二叉樹結構(附例題)

根據中序和前序後序中的任意一種結構就可以確定二叉樹的結構。

因為中序是按照左中右的順序來遍歷的。而前序是按照中左右的順序來確定的,我們可以通過按照前序順序來構建二叉樹,通過中序來確定二叉樹的左子樹和右子樹。後序和中序組合也是這樣,只不過後序需要從後面開始找。

這裡給出兩個例題:

1.前序和中序確定:

資料結構與演算法題目集(中文) 7-23 還原二叉樹 (25 分)

給定一棵二叉樹的先序遍歷序列和中序遍歷序列,要求計算該二叉樹的高度。

輸入格式:

輸入首先給出正整數N(≤50),為樹中結點總數。下面兩行先後給出先序和中序遍歷序列,均是長度為N的不包含重複英文字母(區別大小寫)的字串。

輸出格式:

輸出為一個整數,即該二叉樹的高度。

輸入樣例:

9
ABDFGHIEC
FDHGIBEAC

輸出樣例:

5

 先還原二叉樹,然後求高度。

程式碼如下:

#include <bits/stdc++.h>
using namespace std;
const int maxn=55;
int n;
int loc=0;
char pre[maxn],in[maxn];
struct tree
{
	int data;
	tree* left,*right;
};
int Find (char x)
{
	for (int i=0;i<n;i++)
	{
		if(in[i]==x)
			return i;
	}
	return -1;
}
tree* create (int l,int r)
{
	if(l>r)
	{
		return NULL;
	}
	char root=pre[loc++];
	int m=Find(root);
	tree* t=(tree*)malloc(sizeof(tree));
	t->data=root;
	if(l==r)
	{
		t->left=t->right= NULL;
	}
	else 
	{
		t->left=create(l,m-1);
		t->right=create(m+1,r);
	}
	return t;
}
int Height(tree* root)
{
	if(root==NULL)
	{
		return 0;
	}
	return max(Height(root->left),Height(root->right))+1;
}
int main()
{
	scanf("%d",&n);
	scanf("%s",pre);
	scanf("%s",in);
	tree* root=create(0,n-1);
	printf("%d\n",Height(root));
	return 0;
}

2. PAT (Advanced Level) Practice  1020 Tree Traversals (25 分)

還原二叉樹,然後進行層次遍歷。

程式碼如下:

#include <bits/stdc++.h>
using namespace std;
const int maxn=35;
struct tree
{
	int data;
	tree* left,*right;	
};
int n;
int post[maxn];
int in[maxn];
int loc;
int Find (int x)
{
	for (int i=0;i<n;i++)
	{
		if(in[i]==x)
		 return i;
	}
	return -1;
}
tree* create (int l,int r)
{
	if(l>r)
	{
		return NULL; 
	}
	tree* t=(tree*)malloc(sizeof(tree));
	t->data=post[loc];
	int m=Find(post[loc--]);
	if(l==r)
	{
		t->left=t->right=NULL;
	}
	else 
	{
		t->right=create(m+1,r);
		t->left=create(l,m-1);
	}
	return t;
}
void Traverse (tree* root)
{
	int num=0;
	queue<tree*>q;
	if(root)
		q.push(root);
	while (!q.empty())
	{
		int Size=q.size();
		while (Size--)
		{
			tree* t=q.front();
			q.pop();
			printf("%d",t->data);
			num++;
			if(num==n)
			{
				printf("\n");
			}
			else 
			{
				printf(" ");
			}
			if(t->left)
			{
				q.push(t->left);
			}
			if(t->right)
			{
				q.push(t->right);
			}
		}
	}
}
int main()
{
	scanf("%d",&n);
	loc=n-1;
	for (int i=0;i<n;i++)
	{
		scanf("%d",&post[i]);
	}
	for (int i=0;i<n;i++)
	{
		scanf("%d",&in[i]);
	}
	tree* root=create (0,n-1);
	Traverse(root);
	return 0;
}