璟雯院

珺璟如晔,雯华若锦

用户工具

站点工具


icpc:problems:luogup5018
problems
名称对称二叉树
题目编号P5018
题目链接luogu.com.cn/…
来源Luogu
算法分类树型结构, 递归
难易程度一般般

对称二叉树

想法

判断对称关注点不在于根,在于根的左子树与右子树。当递归判断子树对称时,不仅仅判断当前两个点是否一致,还需要判断左子树的右子树与右子树的左子树是否对称,右子树的右子树与左子树的左子树是否对称。

代码实现

#include<cstdio>
const int N = 1e6+10;
struct node{
	int l, r, val;
};
node tree[N];
int cnt[N], n, ans;
bool check(int x, int y) {
	if(x == -1 && y == -1)
		return true;
	if(x == -1 || y == -1 || tree[x].val != tree[y].val)
		return false;
	if(check(tree[x].l, tree[y].r) && check(tree[x].r, tree[y].l))
		return true;
	return false;
}
void DFS(int x) {
	if(tree[x].l != -1) {
		DFS(tree[x].l);
		cnt[x] += cnt[tree[x].l];
	}
	if(tree[x].r != -1) {
		DFS(tree[x].r);
		cnt[x] += cnt[tree[x].r];
	}
	cnt[x]++;
	if(check(tree[x].l, tree[x].r)) {
		if(ans < cnt[x])ans = cnt[x];
	}
	return ;
}
int main() {
	scanf("%d", &n);
	for(int i=1; i<=n; i++) 
		scanf("%d", &tree[i].val);
	for(int i=1; i<=n; i++) {
		scanf("%d %d", &tree[i].l, &tree[i].r);
	}
	DFS(1);
	printf("%d", ans);
	return 0;
}
/app/www/public/data/pages/icpc/problems/luogup5018.txt · 最后更改: 2024/01/19 11:22 由 温婕莺