题目内容链接:

P5018 对称二叉树题解

 

那么根据题意,上图不是对称二叉树,只有节点7的子树是;

通俗来说,对称二叉树就是已一个节点x为根的子树有穿过x点的对称轴并且对称轴两边的对称点的大小也必须相等,那么这棵树就是对称二叉树。

思路也很简单:递归处理每个节点的子树的节点数size,然后枚举每一个节点的子树来判断是否为对称二叉树。如果一边有节点另一边没有就return剪枝,一旦碰到不一样的节点就剪枝。

特别的,单个节点也是一个对称二叉树。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define LL long long
using namespace std;
int read(){//快读
    int k = 0, f = 1; char c = getchar();
    while(c < '0' || c > '9'){
        if(c == '-') f = -1;
        c = getchar();
    }
    while(c >= '0' && c <= '9'){
        k = k * 10 + c - 48; c = getchar();
    }
    return k * f;
}
int val[1000010], size[1000010], ans;
struct zzz {
    int l, r;
}node[1000010];
int dfs(int pos) {//
    if(pos == -1) return 0;
    size[pos] = dfs(node[pos].l) + dfs(node[pos].r) + 1;
    return size[pos];
}
bool duichen(int ls, int rs) {//判断对称
    if(ls == rs && ls == -1) return 1;
    if(val[ls] == val[rs] && size[ls] == size[rs] && duichen(node[ls].l, node[rs].r) && duichen(node[ls].r, node[rs].l))
        return 1;
    return 0;
}
int main(){
    int n = read();
    for(int i = 1; i <= n; ++i) val[i]=read();
    for(int i = 1; i <= n; ++i)
      node[i].l = read(), node[i].r = read();
    dfs(1);
    for(int i = 1; i <= n; ++i)
        if(duichen(node[i].l, node[i].r)) ans = max(ans, size[i]);
    printf("%d\n", ans);
    return 0;
}

完结

相关文章:

  • 2021-08-24
  • 2022-01-09
  • 2022-02-02
  • 2022-12-23
  • 2021-10-23
  • 2021-11-25
  • 2021-08-28
猜你喜欢
  • 2021-06-25
  • 2021-07-27
  • 2021-11-24
  • 2022-12-23
  • 2022-01-13
相关资源
相似解决方案