给定序列构造二叉排序树,判断是否为同一二叉排序树

#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <iostream>

struct Node {
	Node*lchild;
	Node*rchild;
	int c;
}Tree[110];
int loc;
Node*create()
{
	Tree[loc].lchild = Tree[loc].rchild = NULL;
	return &Tree[loc++];
}
char str1[25], str2[25];
int size1, size2;
char*str;
int*size;

void postOrder(Node*T)
{
	if (T->lchild != NULL)
		postOrder(T->lchild);
	if (T->rchild != NULL)
		postOrder(T->rchild);
	str[(*size)++] = T->c + '0';
	// std::cout << T->c << " ";
}
void inOrder(Node*T)
{
	if (T->lchild != NULL)
		inOrder(T->lchild);
	str[(*size)++] = T->c + '0';
	// std::cout << T->c << " ";
	if (T->rchild != NULL)
		inOrder(T->rchild);
}
Node*insertTree(Node*T, int x)
{
	if (T == NULL)
	{
		T = create();
		T->c = x;
		return T;
	}
	else if (x < T->c)
		T->lchild = insertTree(T->lchild, x);
	else if (x > T->c)
		T->rchild = insertTree(T->rchild, x);
	return T;
}
int main(void)
{
	int n;
	while (scanf_s("%d", &n) != EOF && n != 0)
	{
		loc = 0;
		Node*T = NULL;
		std::cout << "Input the first sequence:" << std::endl;
		std::cin >> size1;
		for (int i = 0; i < size1; i++)
		{
			int x;
			scanf_s("%d", &x);
			T = insertTree(T, x);
		}
		size1 = 0;
		str = str1;
		size = &size1;
		postOrder(T);
		inOrder(T);
		str1[size1] = 0;

		while ((n--) != 0)
		{
			Node*T2 = NULL;
			std::cout << "Input the second sequence:" << std::endl;
			std::cin >> size2;
			for (int i = 0; i < size2; i++)
			{
				int x;
				scanf_s("%d", &x);
				T2 = insertTree(T2, x);
			}
			size2 = 0;
			str = str2;
			size = &size2;
			postOrder(T2);
			inOrder(T2);
			str2[size2] = 0;
			puts(strcmp(str1, str2) == 0 ? "YES" : "NO");
		}
	}


	system("pause");
	return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值