判断一颗二叉树是否是另一颗树的子树。

思路:首先找到值相同的根节点,然后递归判断是否完全相同。
(方便起见,样例还是建一个二叉搜索树)

#include <bits/stdc++.h>
using namespace std;
typedef struct BNode* BTree;
struct BNode
{
    int data;
    BTree left;
    BTree right;
};

void Insert(BTree &t,int data){
    if(!t){
        BTree p=(BTree)malloc(sizeof(BTree));
        p->data=data;
        p->left=NULL;
        p->right=NULL;
        t=p;
    }
    else if(data<t->data)Insert(t->left,data);
    else if(data>=t->data)Insert(t->right,data);
}

bool Judge(BTree parent,BTree child){
    if(child==NULL)return true;
    if(parent==NULL)return false;
    if(parent->data==child->data)return Judge(parent->left,child->left)&&Judge(parent->right,child->right);
    return false;
}
bool JudgeTree(BTree parent,BTree child){
    if(!parent||!child)return false;
    if(Judge(parent,child))return true;
    return Judge(parent->left,child)||Judge(parent->right,child);
}
int main()
{
    int n,m;
    int a[1001],b[1001];
    cin>>n>>m;
    BTree t=NULL,child=NULL;
    for(int i=0;i<n;i++){
        cin>>a[i];
        Insert(t,a[i]);
    }
    for(int i=0;i<m;i++){
        cin>>b[i];
        Insert(child,b[i]);
    }
    if(JudgeTree(t,child))cout<<"YES"<<endl;
    else cout<<"NO"<<endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值