当前位置:   article > 正文

【洛谷P5018】对称二叉树

洛谷 p5018

题目大意:定义对称二叉树为每个节点的左右子树交换后与原二叉树仍同构的二叉树,求给定的二叉树的最大对称二叉子树的大小。

代码如下

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int maxn=1e6+10;
  4. struct node{
  5. int l,r,size,val;
  6. }t[maxn];
  7. int n,ans;
  8. void read_and_parse(){
  9. scanf("%d",&n);
  10. for(int i=1;i<=n;i++)scanf("%d",&t[i].val);
  11. for(int i=1,l,r;i<=n;i++){
  12. scanf("%d%d",&l,&r);
  13. if(l!=-1)t[i].l=l;
  14. if(r!=-1)t[i].r=r;
  15. }
  16. }
  17. bool check(int x,int y){//递归判断是否同构
  18. if(!x&&!y)return 1;
  19. else if(t[x].val^t[y].val)return 0;
  20. else return check(t[x].l,t[y].r)&&check(t[x].r,t[y].l);
  21. }
  22. void dfs(int x){
  23. t[x].size=1;
  24. if(t[x].l)dfs(t[x].l),t[x].size+=t[t[x].l].size;
  25. if(t[x].r)dfs(t[x].r),t[x].size+=t[t[x].r].size;
  26. if(check(t[x].l,t[x].r))ans=max(ans,t[x].size);
  27. }
  28. void solve(){
  29. dfs(1);
  30. printf("%d\n",ans);
  31. }
  32. int main(){
  33. read_and_parse();
  34. solve();
  35. return 0;
  36. }

转载于:https://www.cnblogs.com/wzj-xhjbk/p/9944421.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/731960
推荐阅读
相关标签
  

闽ICP备14008679号