数据结构与算法题目集7-3——树的同构

版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/84678266

我的数据结构与算法题目集代码仓:https://github.com/617076674/Data-structure-and-algorithm-topic-set

原题链接:https://pintia.cn/problem-sets/15/problems/711

题目描述:

知识点:递归

思路:递归判断两棵树是否同构

递归终止条件

(1)当head1 == -1 且head2 == -1时,两棵树都是空树,返回true。

(2)当head1 == -1 且head2 != -1时,一棵是空树,另一棵不是空树,返回false。

(3)当head1 != -1 且head2 == -1时,一棵是空树,另一棵不是空树,返回false。

递归过程

(4)当head1和head2均不为-1时,

如果head1的左子树和head2的左子树同构,且head1的右子树和head2的右子树同构,返回true。

如果head1的左子树和head2的右子树同构,且head1的右子树和head2的左子树同构,返回true。

如果以上两种情况都不满足,返回false。

时间复杂度和空间复杂度均是O(N)。

注意点:用scanf("%c", &data);读取输出字符时,需要用getchar()读取中间的空格符以及行末的换行符

C++代码:

#include<iostream>

using namespace std;

struct node {
	char data;
	int lchild, rchild;
};

int N;
node Node1[10], Node2[10];

int read(node Node[]);
bool judge(int head1, int head2);

int main() {
	int head1 = read(Node1);
	int head2 = read(Node2);
	if(judge(head1, head2)) {
		printf("Yes\n");
	} else {
		printf("No\n");
	}
	return 0;
}

int read(node Node[]) {
	scanf("%d", &N);
	getchar();
	char data, lchild, rchild;
	bool show[N];
	fill(show, show + N, false);
	for(int i = 0; i < N; i++) {
		scanf("%c", &data);
		getchar();
		scanf("%c", &lchild);
		getchar();
		scanf("%c", &rchild);
		getchar();
		Node[i].data = data;
		if(lchild == '-') {
			Node[i].lchild = -1;
		} else {
			Node[i].lchild = lchild - '0';
			show[lchild - '0'] = true;
		}
		if(rchild == '-') {
			Node[i].rchild = -1;
		} else {
			Node[i].rchild = rchild - '0';
			show[rchild - '0'] = true;
		}
	}
	for(int i = 0; i < N; i++) {
		if(!show[i]) {
			return i;
		}
	}
	return -1;
}

bool judge(int head1, int head2) {
	if(head1 == -1 && head2 == -1) {
		return true;
	} else if(head1 == -1 && head2 != -1) {
		return false;
	} else if(head1 != -1 && head2 == -1) {
		return false;
	} else {
		if(Node1[head1].data != Node2[head2].data) {
			return false;
		} else { 
			return (judge(Node1[head1].lchild, Node2[head2].lchild) && judge(Node1[head1].rchild, Node2[head2].rchild)) 
				|| (judge(Node1[head1].lchild, Node2[head2].rchild) && judge(Node1[head1].rchild, Node2[head2].lchild)); 
		}
	}

}

C++解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/84678266
今日推荐