笔试面试编程题

1. 判断二叉树是否相同,左右孩子互换也认为相同,要求纸上写出全部代码

#include <iostream>

using namespace std;

typedef struct AA{
    AA *l, *r;
    int data;
    
}Node;
Node tree1[10];
Node tree2[10];
/*
bool bitree_cmp(Node *n1, Node *n2)
{
    int cnt1 = 0, cnt2=0;
    bool ans = false;
    if ( n1 == NULL && n2 == NULL )
        return true;
    if ( (n1 == NULL && n2 != NULL) || (n1 != NULL && n2 == NULL))
        return false;
    if ( n1->data != n2->data )
        return false;
    if ( n1->l )
        ++cnt1;
    if ( n2->r )
        ++cnt1;
    if ( n2->l )
        ++cnt2;
    if ( n2->r )
        ++cnt2;
    if ( cnt1 != cnt2 )
        return false;
    if ( cnt1 == 0 )
        return true;
    ans = bitree_cmp(n1->l, n2->l) && bitree_cmp(n1->r, n1->r);
    if ( ans )
        return true;
    ans = bitree_cmp(n1->l, n2->r) && bitree_cmp(n1->r, n2->l);
    return ans;
}
*/
bool bitree_cmp(Node *n1, Node *n2)
{
    if ( n1 == NULL && n2 == NULL )
        return true;
    if ( n1 != NULL && n2 != NULL )
    {
        if ( n1->data == n2->data )
        {
            return ( bitree_cmp(n1->l, n2->l)&&bitree_cmp(n1->r, n2->r) ) || ( bitree_cmp(n1->l, n2->r)&&bitree_cmp(n1->r, n2->l) );     
        }    
    }
    return false; 
} 


void read_data(Node *tree, int i)
{
    int data, l , r;
    scanf("%d%d%d",&data, &l, &r);
    tree[i].data = data;
    if ( l )
        tree[i].l = &tree[l];
    else
        tree[i].l = NULL;
    if ( r )
        tree[i].r = &tree[r];    
    else
        tree[i].r = NULL;     
}

int main()
{
    int n1, n2;
    int l, r, data;
    int i = 0;
    scanf("%d", &n1);
    while(n1--)
    {
       read_data(tree1, i); 
       ++i;
    }
    scanf("%d", &n2);
    i = 0;
    while(n2--)
    {
       read_data(tree2, i);
       ++i; 
    }   
    cout<<bitree_cmp(tree1, tree2)<<endl;
    cin>>i;
    
    
    return 0;
}

/*
测试数据: 
       1                      1
    2     2               2        2
  3  4   6   7          6  7     4   3  
从这开始: 
7
1 1 2
2 3 4
2 5 6
3 0 0
4 0 0
6 0 0
7 0 0

7
1 1 2
2 3 4
2 5 6
7 0 0
6 0 0
3 0 0
4 0 0

7
1 1 2
2 3 4
2 5 6
3 0 0
4 0 0
6 0 0
7 0 0

7
1 1 2
2 3 4
2 5 6
3 0 0
4 0 0
6 0 0
7 0 0



*/

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值