【数据结构·考研】相似的二叉树 & 相同的二叉树

相似的二叉树

如果两棵二叉树在结构上相同,则认为它们是相似的。

这道题用递归的方式来做最简单,递归的遍历两棵二叉树相同的位置。两棵二叉树 t1 和 t2 皆为空或者皆不空且 t1 的左右子树和 t2 的左右子树分别相似,则可以判断出 t1 和 t2 相似。

//相似的树
bool isSimilarTree(Tree& t1,Tree& t2){
	if(t1 == NULL && t2 == NULL) return true;
	if(!(t1 && t2)) return false; //如果t1和t2中有一个为空,返回false
	return  isSimilarTree(t1->left,t2->left) && isSimilarTree(t1->right,t2->right);
}

相同的二叉树

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

只需要把上述代码中的第二个 if 中判断条件再加上判断两棵树的对应位置的值是否相同。

//相同的树
bool isSameTree(Tree& t1,Tree& t2){
	if(t1 == NULL && t2 == NULL) return true;
	if(!(t1 && t2) || t1->val != t2->val) return false; //如果t1和t2中有一个为空或者值不相等,返回false
	return  isSameTree(t1->left,t2->left) && isSameTree(t1->right,t2->right);
}

完整代码如下:

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

typedef struct node{
	char val;
	struct node* left;
	struct node* right;
}TreeNode,*Tree;

//相似的树
bool isSimilarTree(Tree& t1,Tree& t2){
	if(t1 == NULL && t2 == NULL) return true;
	if(!(t1 && t2)) return false; //如果t1和t2中有一个为空,返回false
	return  isSimilarTree(t1->left,t2->left) && isSimilarTree(t1->right,t2->right);
} 
//相同的树
bool isSameTree(Tree& t1,Tree& t2){
	if(t1 == NULL && t2 == NULL) return true;
	if(!(t1 && t2) || t1->val != t2->val) return false; //如果t1和t2中有一个为空或者值不相等,返回false
	return  isSameTree(t1->left,t2->left) && isSameTree(t1->right,t2->right);
}

void CreateTree(Tree& t){
	char x;
	cin>>x;
	if(x == '#') t = NULL; 
	else{
		t = new TreeNode; 
		t->val = x;  
		CreateTree(t->left); 
		CreateTree(t->right); 
	}
} 
 
int main(){
	Tree t1;
	Tree t2;
	CreateTree(t1);
	/*
	   a b d # # e # # c g # # #
	*/
	CreateTree(t2);
	/*
	   a b d # # e # # c f # # #
	*/
	cout<<"相似吗:";
	cout<<isSimilarTree(t1,t2)<<endl;
	cout<<"相同吗:"; 
    cout<<isSameTree(t1,t2)<<endl;
}

运行结果:

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jiawen9

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值