[数据结构] 二叉树的等价判断与复制

输入                                   A

                           B                          C

                D               E           F             G

          H        I       J

以先序遍历,用“#”表示为空,输入ABDH##I##EJ###CF##G##

再输入一棵二叉树,进行判断

#include <iostream>
#include <stack>
#include <queue> 
using namespace std;  

typedef char Elementtype;

typedef struct node  
{  
    struct node *lchild;  
    struct node *rchild;  
    Elementtype data; 
}BiTreeNode, *BTREE;  
      
void CreateBTree(BTREE &T) //先序顺序建立二叉树 
{  
    char c;  
    cin >> c;  
    if('#' == c)  
      T = NULL;  
    else  
    {  
        T = new node;  
        T->data = c;

        CreateBTree(T->lchild);  //递归建立 
        CreateBTree(T->rchild);  
    }  
}

int IsEmpty(BTREE root)
{
    if (root == NULL)
      return 1;
    else
      return 0;
}

bool Equal(BTREE firstbt,BTREE secondbt)//判断两棵二叉树是否等价 
{
	bool x;
	x = false;
	if((IsEmpty(firstbt))&&(IsEmpty(secondbt)))
	  x = true;
    else if(!IsEmpty(firstbt)&&!IsEmpty(secondbt))
      if((firstbt->data)==(secondbt->data))
        if(Equal(firstbt->lchild,secondbt->lchild))
          x = Equal(firstbt->rchild,secondbt->rchild);
    return x;
}

BTREE CopyBT(BTREE oldtree)
{
	BTREE temp;
	if(oldtree==NULL)
	  return NULL;	
	else
	{
		temp = new node;
		temp->data = oldtree->data;
		temp->lchild = CopyBT(oldtree->lchild);
		temp->rchild = CopyBT(oldtree->rchild);
		return temp;
	}	
}

int main()  
{  
    BTREE T1,T2;
	BTREE T3;  
    CreateBTree(T1); 
    CreateBTree(T2); 
    if(Equal(T1,T2))
      cout << "Right!" << endl;
    else
	  cout << "No!" << endl;
	
	T3 = CopyBT(T2); 
    if(Equal(T1,T3))
      cout << "Right!" << endl;
    else
	  cout << "No!" << endl;
    return 0; 
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值