对称二叉树

思路

递归就好了,确实,递归就好了

一个递归去dfs,另一个去递归check,check注意要对称进行左右子树的访问,
然后整体复杂度因该是的。

代码

/*
  Author : lifehappy
*/
#include <bits/stdc++.h>

using namespace std;

const int N = 2e6 + 10;

int lson[N], rson[N], value[N], sz[N], r[N], rk[N], dep[N], n, ans, tot;

bool judge(int u, int v) {
    if(u == -1 && v == -1) return true;
    return (u != -1 && v != -1 && value[u] == value[v] && judge(lson[u], rson[v]) && judge(rson[u], lson[v]));
}

void dfs(int rt, int fa) {
    sz[rt] = 1;
    if(lson[rt] != -1) {
        dfs(lson[rt], rt);
        sz[rt] += sz[lson[rt]];
    }
    if(rson[rt] != -1) {
        dfs(rson[rt], rt);
        sz[rt] += sz[rson[rt]];
    }
    if(judge(lson[rt], rson[rt])) {
        ans = max(ans, sz[rt]);
    }
}

int main() {
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    // ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    scanf("%d", &n);
    for(int i = 1; i <= n; i++) {
        scanf("%d", &value[i]);
    }
    for(int i = 1; i <= n; i++) {
        scanf("%d %d", &lson[i], &rson[i]);
    }
    ans = 1;
    dfs(1, 0);
    printf("%d\n", ans);
    return 0;
}