Thinking symmetrical binary tree structure + (Los Valley P5018)

Symmetrical binary tree

Title Description

The right to have a little bit of the root of the tree if the following conditions are met Xuan Xuan were called symmetric binary tree:

Binary tree;
the same left and right subtrees of all these trees switching nodes, the new tree and the original tree structure corresponding to the location points and equal rights.

Now we are given a binary tree, I hope you find it a sub-tree, the tree is symmetrical sub binary tree, and a maximum number of nodes. Please tree output sub-tree nodes.

Note: Only the roots of the trees are symmetrical binary tree. In this problem convention, to a sub-root node of T "subtree" means: binary tree node T and all of its successor nodes.

The input format
of the first line of a positive integer n, the number of a given node of a tree, a predetermined node number 1~n, where 1 is the root node.

The second row of n positive integers, separated by a space, the i-th positive integer weights vi for node i.

Next n lines of two positive integers li, ri, respectively, left and right child node number i. If the left / right child does not exist, -1 -1 representation. Separated by a space between the two numbers.

Output Format

Total output file row contains an integer indicating the maximum tree given two symmetrical fork tree nodes.


Find all subtrees is determined whether symmetry (symmetric tree depends on whether it is all subtrees are symmetric), find the maximum symmetric subtree;

Recursively traverse the tree is obvious, is just beginning to think about the string right sub-tree and every single tree can be composed of values ​​are calculated, and then determine whether the left and right sub-tree of the same string, but it TLE and WA;

Positive Solutions for the root of each subtree of nodes which left and right subtrees is assumed to be l, r, then it should satisfy
w [L [l]] = w [R [r]] && w [R [l]] = w [L [r]];

#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define ls k<<1
#define rs k<<1|1
#define inf 0x3f3f3f3f
using namespace std;
const int N=1000010;
const int M=1000100;
const int mod=1e5+7;
int n,w[N],L[N],R[N],size[N],ans;
int dfs(int fa){
	size[fa]=1;
	if(L[fa]!=-1) size[fa]+=dfs(L[fa]);
	if(R[fa]!=-1) size[fa]+=dfs(R[fa]);
	return size[fa];
}
bool judge(int l,int r){
	if(l==-1&&r==-1) return true;
	if(l!=-1&&r!=-1&&w[l]==w[r]&&judge(L[l],R[r])&&judge(R[l],L[r])) return true;
	return false;
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++) scanf("%d",&w[i]);
	for(int i=1;i<=n;i++) scanf("%d%d",&L[i],&R[i]);
	dfs(1);
	for(int i=1;i<=n;i++){
		if(judge(L[i],R[i])){
			ans=max(size[i],ans);
		}
	}
	cout<<ans<<endl;
    return 0;
}
Published 264 original articles · won praise 46 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_44291254/article/details/105103317