题目大意:定义对称二叉树为每个节点的左右子树交换后与原二叉树仍同构的二叉树,求给定的二叉树的最大对称二叉子树的大小。
代码如下
- #include <bits/stdc++.h>
- using namespace std;
- const int maxn=1e6+10;
-
- struct node{
- int l,r,size,val;
- }t[maxn];
- int n,ans;
-
- void read_and_parse(){
- scanf("%d",&n);
- for(int i=1;i<=n;i++)scanf("%d",&t[i].val);
- for(int i=1,l,r;i<=n;i++){
- scanf("%d%d",&l,&r);
- if(l!=-1)t[i].l=l;
- if(r!=-1)t[i].r=r;
- }
- }
-
- bool check(int x,int y){//递归判断是否同构
- if(!x&&!y)return 1;
- else if(t[x].val^t[y].val)return 0;
- else return check(t[x].l,t[y].r)&&check(t[x].r,t[y].l);
- }
-
- void dfs(int x){
- t[x].size=1;
- if(t[x].l)dfs(t[x].l),t[x].size+=t[t[x].l].size;
- if(t[x].r)dfs(t[x].r),t[x].size+=t[t[x].r].size;
- if(check(t[x].l,t[x].r))ans=max(ans,t[x].size);
- }
-
- void solve(){
- dfs(1);
- printf("%d\n",ans);
- }
-
- int main(){
- read_and_parse();
- solve();
- return 0;
- }