程序员面试题精选100题(50)-树的子结构.

本文介绍了一种构建二叉树的方法,并详细解释了如何判断一个树是否包含另一个树作为其子结构。通过输入前序和中序序列,实现二叉树的重建,并进一步验证两个树之间是否存在子结构关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 程序员面试题精选100题(50)-树的子结构.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

struct TNode{
	char chValue;
	TNode *leftChild;
	TNode *rightChild;
};
TNode* rebuildTree(char *preOrder,int start1,char *midOrder,int start2,int n)//根据前序和中序建立二叉树 长度为N
{
	TNode *root;
	if(n==0) return NULL;
	root = new TNode;
	int pivet;
	char chroot;
	chroot=preOrder[start1];
	root->chValue = chroot;
	for(int i=start2;i<start2+n;i++)//include start1 
	{
		if(midOrder[i]==chroot) { pivet = i;break;}
	}
	if(pivet-start2>0)
		root->leftChild=rebuildTree(preOrder,start1+1,midOrder,start2,pivet-start2);
	else root->leftChild = NULL;
	if(n-pivet+start2-1>0)//pivet-start2 is the half number,
		root->rightChild=rebuildTree(preOrder,start1+1+pivet-start2,midOrder,pivet+1,n-pivet+start2-1);
	else root->rightChild = NULL;
	return root;
}
void preprint(TNode *root)
{
	if(root!=NULL)
	{
		cout<<root->chValue<<" ";
		preprint(root->leftChild);
		preprint(root->rightChild);
	}
}
bool isContain(TNode* rootparent,TNode* rootchild)
{
	if (rootparent==NULL&&rootchild!=NULL)
	{
		return false;
	}
	else
		if (rootparent!=NULL&&rootchild!=NULL)
		{
			if (rootparent->chValue==rootchild->chValue)
			{
				return isContain(rootparent->leftChild,rootchild->leftChild)&isContain(rootparent->rightChild,rootchild->rightChild);
			}
			else
			{
				if(isContain(rootparent->leftChild,rootchild))
					return true;
				else
					return isContain(rootparent->rightChild,rootchild);
			}
		}
		else
			return true;// rootparent==NULL&&rootchild==NULL or rootparent!=NULL&&rootchild==NULL
}
int _tmain(int argc, _TCHAR* argv[])
{
	TNode* rootparent,*rootchild;
	int n,m;
	cout<<"input n"<<endl;
	cin>>n;
	char *preOrder=new char[n];
	char *midOrder=new char[n];
	cout<<"input preorder1"<<endl;
	for(int i=0;i<n;i++)
		cin>>preOrder[i];
	cout<<"input midorder1"<<endl;
	for(int i=0;i<n;i++)
		cin>>midOrder[i];
	rootparent=rebuildTree(preOrder,0,midOrder,0,n);
	//preprint(rootparent);

	cout<<endl<<"input m"<<endl;
	cin>>m;
	char *preOrder2=new char[m];
	char *midOrder2=new char[m];
	cout<<"input preorder2"<<endl;
	for(int i=0;i<m;i++)
		cin>>preOrder2[i];
	cout<<"input midorder2"<<endl;
	for(int i=0;i<m;i++)
		cin>>midOrder2[i];
	rootchild=rebuildTree(preOrder2,0,midOrder2,0,m);
	//preprint(rootchild);

	cout<<isContain(rootparent,rootchild)<<endl;
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值