Is It a Binary Search Tree (25)

題目分析:

1、要求根據給出的數字建立二叉樹

2、看看給出的數字序列是不是先序遍歷,是則給出後序遍歷

3、看看給出的數字序列是不是鏡像的先序遍歷,是則給出鏡像的後序遍歷


注意地方:

手寫解題的時候,要注意鏡像是左邊大於等於根節點,右邊小於根節點,完全鏡像。


遍歷方法:

1、先序:根節點,左兒子調用遞歸,右兒子調用遞歸

2、中序、後序類似

void PreOrder(Tree *root)
{
	if (root != NULL)
	{
		result1[count1++] = root->key;
		PreOrder(root->left);
		PreOrder(root->right);
	}
}

解題代碼:

#include "iostream"
#include "vector"
#include "string"
#include "cstring"
using namespace std;

struct Tree
{
	int key;
	Tree *left;
	Tree *right;
	Tree() {
		key = -1;
		left = NULL;
		right = NULL;
	}
};

int result1[1000], result2[1000];
int result3[1000], result4[1000];
int count1 = 0, count2 = 0;
int count3 = 0, count4 = 0;
void PreOrder(Tree *root)
{
	if (root != NULL)
	{
		result1[count1++] = root->key;
		PreOrder(root->left);
		PreOrder(root->right);
	}
}
void MirrorPreOrder(Tree *root)
{
	if (root != NULL)
	{
		result2[count2++] = root->key;
		MirrorPreOrder(root->right);
		MirrorPreOrder(root->left);
	}
}

void PostOrder(Tree *root)
{
	if (root != NULL)
	{
		PostOrder(root->left);
		PostOrder(root->right);
		result3[count3++] = root->key;
	}
}

void MirrorPostOrder(Tree *root)
{
	if (root != NULL)
	{
		MirrorPostOrder(root->right);
		MirrorPostOrder(root->left);
		result4[count4++] = root->key;
	}
}

int main()
{
	int N;
	int data[1000];
	cin >> N;
	for (int i = 0; i < N; i++)
		cin >> data[i];
	Tree *root = (Tree*)malloc(sizeof(Tree));
	root->key = data[0];
	root->left = NULL;
	root->right = NULL;
	Tree *operat = root;
	for (int i = 1; i < N; i++)
	{
		Tree *temp = root;
		while (1)
		{
			if (temp->key > data[i])
			{
				if (temp->left == NULL)
				{
					temp->left = (Tree*)malloc(sizeof(Tree));
					temp = temp->left;
					temp->key = data[i];
					temp->left = NULL;
					temp->right = NULL;
					break;
				}
				else
					temp = temp->left;
			}
			else
			{
				if (temp->right == NULL)
				{
					temp->right = (Tree*)malloc(sizeof(Tree));
					temp = temp->right;
					temp->key = data[i];
					temp->left = NULL;
					temp->right = NULL;
					break;
				}
				else
					temp = temp->right;

			}
		}
	}
	bool mirror = true;
	bool pre = true;
	PreOrder(root);
	MirrorPreOrder(root);
	for (int i = 0; i < N; i++)
	{
		if (result1[i] != data[i])
		{
			pre = false;
		}
		if (result2[i] != data[i])
		{
			mirror = false;
		}
	}
	if (pre == false && mirror == false)
	{
		cout << "NO";
	}
	else if (pre == true)
	{
		cout << "YES" << endl;
		PostOrder(root);
		for (int i = 0; i < N - 1; i++)
			cout << result3[i] << ' ';
		cout << result3[N - 1];
	}
	else
	{
		cout << "YES"<<endl;
		MirrorPostOrder(root);
		for (int i = 0; i < N - 1; i++)
			cout << result4[i] << ' ';
		cout << result4[N - 1];
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章