P5018-对称二叉树

 1 #include <bits/stdc++.h>
 2 #define _for(i,a,b) for(int i = (a);i < b;i ++)
 3 typedef long long ll;
 4 using namespace std;
 5 int N;
 6 int vallist[1000003];
 7 int stlist[2][1000003];
 8 int rnt = 1;
 9 inline ll read()
10 {
11     ll ans = 0;
12     char ch = getchar(), last = ' ';
13     while(!isdigit(ch)) last = ch, ch = getchar();
14     while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
15     if(last == '-') ans = -ans;
16     return ans;
17 }
18 inline void write(ll x)
19 {
20     if(x < 0) x = -x, putchar('-');
21     if(x >= 10) write(x / 10);
22     putchar(x % 10 + '0');
23 }
24 struct TreeNode
25 {
26     int val;
27     TreeNode *left;
28     TreeNode *right;
29 };
30 TreeNode* build(int cur)
31 {
32     TreeNode* t = (TreeNode*)malloc(sizeof(TreeNode));
33     t->val = vallist[cur];
34     if(stlist[0][cur]==-1)
35         t->left = NULL;
36     else
37         t->left = build(stlist[0][cur]-1);
38     if(stlist[1][cur]==-1)
39         t->right = NULL;
40     else
41         t->right = build(stlist[1][cur]-1);
42     return t;
43 }
44 bool same(TreeNode* root1,TreeNode* root2)
45 {
46     if(!root1&&!root2)
47         return true;
48     if(!root1||!root2)
49         return false;
50     if(root1->val!=root2->val)
51         return false;
52     return same(root1->left,root2->right) && same(root1->right,root2->left);
53 }
54 int count(TreeNode* root)
55 {
56     if(!root)
57         return 0;
58     int k1 = count(root->left);
59     int k2 = count(root->right);
60     return k1+k2+1;
61 }
62 void f(TreeNode* root)
63 {
64     if(!root)
65         return ;
66     f(root->left);
67     f(root->right);
68     if(same(root,root))
69         rnt = max(rnt,count(root));
70 }
71 int main()
72 {
73     TreeNode* root;
74     N = read();
75     _for(i,0,N)
76         vallist[i] = read();
77     _for(i,0,N)
78         _for(j,0,2)
79             stlist[j][i] = read();
80     root = build(0);
81     f(root);
82     write(rnt);
83     return 0;
84 }

 

转载于:https://www.cnblogs.com/Asurudo/p/11289975.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值