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];
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值