输入俩颗二叉树A和B,判断B是不是A的子结构。
思路:1.在树A中找到和B的根节点的值一样的节点R 2.再判断树A中以R为根节点的子树是不是包含和树B一样的结构
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
struct BinaryTree
{
int m_value;
struct BinaryTree* leftChild;
struct BinaryTree* rightChild;
};
//index 设置为&类型 则此函数调用后index会发生改变
BinaryTree* createTree(BinaryTree* root,int* s,int& index)
{
if(s[index]==0) //如果第一个是0则代表为空
return NULL;
root=new BinaryTree;
root->m_value=s[index];
root->leftChild=createTree(root->leftChild,s,++index);
root->rightChild=createTree(root->rightChild,s,++index);
return root;
}
//前序遍历
void preTraverse(BinaryTree* root)
{
if(root==NULL)
return;
cout<<root->m_value<<endl;
preTraverse(root->leftChild);
preTraverse(root->rightChild);
}
//判断相同根节点后面的结构是否相同
bool DoesTree1HaveTree2(BinaryTree* root1,BinaryTree* root2)
{
//此处的判断结构顺序很重要 顺序不能颠倒 否则会出错
if(root2==NULL) //判断是否达到了root2的最终的叶子
return true; //如果条件走到这步说明之前的结构都相同 则完成遍历判断 直接返回true
if(root1==NULL) //判断是否达到了root1的最终叶子节点
return false;//如果条件走到了这步说明root2还没有到达最终的叶子时 root1没有比较的结构了 则root1不存在root2返回false
if(root1->m_value!=root2->m_value) //如果都不是最终叶子 则判断俩者是否相等
return false;
//如果相等则继续遍历查找剩下的结构
return DoesTree1HaveTree2(root1->leftChild,root2->leftChild) &&
DoesTree1HaveTree2(root1->rightChild,root2->rightChild);
}
//先判断是否有相同的根节点
bool HasSubtree(BinaryTree* root1,BinaryTree* root2)
{
bool result =false;
if(root1!=NULL && root2!=NULL) //判断俩个根节点是不是空节点
{
if(root1->m_value==root2->m_value)
result=DoesTree1HaveTree2(root1,root2);
//如果子节点不相同 则继续遍历查找
if(!result)
result=HasSubtree(root1->leftChild,root2);
if(!result)
result=HasSubtree(root1->rightChild,root2);
}
return result;
}
int main()
{
//输入的时候,不能忘记用0来补充NULL值
int Tree1[]={8,8,9,0,0,2,4,0,0,7,0,0,7,0,0};
int Tree2[]={8,9,0,0,2,0,0};
//int Tree1[]={1,0,0}; //只有一个根节点1
//int Tree2[]={1,0,0};
int index1=0;
int index2=0;
BinaryTree* root1=NULL;
root1=createTree(root1,Tree1,index1);
BinaryTree* root2=NULL;
root2=createTree(root2,Tree2,index2);
preTraverse(root1);
cout<<"----"<<endl;
preTraverse(root2);
cout<<"----"<<endl;
if(HasSubtree(root1,root2))
cout<<"root1 has root2";
else
cout<<"root1 don't has root2";
return 0;
}