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

相似的二叉树

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

这道题用递归的方式来做最简单,递归的遍历两棵二叉树相同的位置。两棵二叉树 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;
}

运行结果:

猜你喜欢

转载自blog.csdn.net/cjw838982809/article/details/108328179