题目:二叉树的结点定义如下:
struct Tree
{
int m_value;
TreeNode* m_left;
TreeNode* m_right;
};
输入两棵二叉树A和B,判断树B是不是A的子结构。
例如,下图中的两棵树A和B,由于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;
}