第四十二题 树的子结构

题目:二叉树的结点定义如下:

struct Tree

{

        int m_value;

        TreeNode* m_left;

        TreeNode* m_right;

};

输入两棵二叉树AB,判断树B是不是A的子结构。

例如,下图中的两棵树AB,由于A中有一部分子树的结构和B是一样的,因此B就是A的子结构。

                 1                                                   8
               /    \                                               /    \
              8    7                                             9    2
            /    \
           9    2
                /  \
               4  7

//判断树是否为子结构
#include <iostream>
#include <boost\shared_ptr.hpp>
using namespace std;
struct Tree
{
	int m_value;
	Tree *m_left;
	Tree *m_right;
};
Tree* CreateBinaryTreeNode(int value)
{
	Tree* pNode = new Tree();
	pNode->m_value = value;
	pNode->m_left = nullptr;
	pNode->m_right = nullptr;

	return pNode;
}

void ConnectTreeNodes(Tree* pParent, Tree* pLeft, Tree* pRight)
{
	if(pParent != nullptr)
	{
		pParent->m_left = pLeft;
		pParent->m_right = pRight;
	}
}
//节点的值相同时,调用这个来判断其子节点是否相同
bool getsubTree(Tree *Node1,Tree *Node2)
{
	if (Node2==nullptr)
	{
		return true;
	}
	if (Node1==nullptr)
	{
		return false;
	}
	if (Node1->m_value!=Node2->m_value)
	{
		return false;
	}
	return getsubTree(Node1->m_left,Node2->m_left)&&getsubTree(Node1->m_right,Node2->m_right);
}
//求解Node2是否为Node1的子树
bool SubTree(Tree *Node1,Tree *Node2)
{
	if ((Node1==nullptr&&Node2!=nullptr)||(Node1!=nullptr&&Node2==nullptr))
	{
		return false;
	}
	if (Node1==nullptr&&Node2==nullptr)
	{
		return true;
	}
	bool result=false;
	if (Node1->m_value==Node2->m_value)
	{
		result=getsubTree(Node1,Node2);//当父节点的值时
	}
	if (!result&&Node1->m_left!=nullptr)
	{
		result=SubTree(Node1->m_left,Node2);
	}
	if (!result&&Node1->m_right!=nullptr)
	{
		result=SubTree(Node1->m_right,Node2);
	}
	return result;
}
int main()
{
	Tree* pNodeA1 = CreateBinaryTreeNode(1);
	Tree* pNodeA2 = CreateBinaryTreeNode(8);
	Tree* pNodeA3 = CreateBinaryTreeNode(7);
	Tree* pNodeA4 = CreateBinaryTreeNode(9);
	Tree* pNodeA5 = CreateBinaryTreeNode(2);
	Tree* pNodeA6 = CreateBinaryTreeNode(4);
	Tree* pNodeA7 = CreateBinaryTreeNode(7);
	ConnectTreeNodes(pNodeA1, pNodeA2, pNodeA3);
	ConnectTreeNodes(pNodeA2, pNodeA4, pNodeA5);
	ConnectTreeNodes(pNodeA5, pNodeA6, pNodeA7);//构建大树
	Tree* pNodeB1 = CreateBinaryTreeNode(8);
	Tree* pNodeB2 = CreateBinaryTreeNode(9);
	Tree* pNodeB3 = CreateBinaryTreeNode(2);
	ConnectTreeNodes(pNodeB1, pNodeB2, pNodeB3);//构建子树
	bool k=SubTree(pNodeA1,pNodeB1);
	cout<<(k==true)?1:0;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值