赞
踩
知识点:二叉树
难度:4
这个题是求一个二叉树里面最大的对称子树的节点个数,不会什么树哈希,就用了暴力方法,虽然数据很大,但是这时普及组的题,不太会考察什么高级的知识,就用了暴力,就是一遍递归,一遍判断,更新答案,如果当前节点是对称的,那么就不向下递归了,然后问题就分解成了怎么判断一个二叉树是不是对称的,这个我们可以用原来的二叉树构建出的一棵所有左右孩子都对换的二叉树来与原二叉树做比较,分类讨论就行了,比较的过程中来记录节点数,空的时候不要记录,
- #include <bits/stdc++.h>
-
- using namespace std;
-
- const int N = 1e6 + 5;
-
- struct node {
- int val, l, r;
- } tr[N];
-
- int cnt, ans;
-
- bool judge(int root1, int root2) {
- if (root1 == -1 && root2 == -1) return true;
- if (root1 == -1 && root2 != -1 || root1 != -1 && root2 == -1) return false;
- cnt++;
- if (tr[root1].val != tr[root2].val) return false;
- return judge(tr[root1].l, tr[root2].r) && judge(tr[root1].r, tr[root2].l);
- }
-
- void solve(int root) {
- if (root == -1) return;
- cnt = 0;
- bool flag = judge(root, root);
- if (flag) { ans = max(ans, cnt); return; }
- solve(tr[root].l);
- solve(tr[root].r);
- }
-
- int main() {
- int n;
- cin >> n;
- for (int i = 1; i <= n; i++) cin >> tr[i].val;
- for (int i = 1; i <= n; i++) cin >> tr[i].l >> tr[i].r;
- solve(1);
- cout << ans;
- return 0;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。