对称二叉树&&dfs&&java-牛客

题意

详情请跟随–题目链接: https://ac.nowcoder.com/acm/contest/19859/R
 一棵有点权的有根树如果满足以下条件,则被轩轩称为对称二叉树:
1. 二叉树;
2. 将这棵树所有节点的左右子树交换,新树和原树对应位置的结构相同且点权相等。


Input

 第一行一个正整数 𝑛,表示给定的树的节点的数目,规定节点编号 1~n,其中节点1 是树根。
第二行 𝑛 个正整数,用一个空格分隔,第 𝑖 个正整数 𝑣𝑖 代表节点 𝑖 的权值。
接下来 𝑛 行,每行两个正整数 𝑙 , 𝑟 ,分别表示节点 𝑖 的左右孩子的编号。如果不存在左 / 右孩子,则以 −1 表示。两个数之间用一个空格隔开。


Output

 输出文件共一行,包含一个整数,表示给定的树的最大对称二叉子树的节点数。

Example Input

10
2 2 5 5 5 5 4 4 2 3
9 10
-1 -1
-1 -1
-1 -1
-1 -1
-1 2
3 4
5 6
-1 -1
7 8

Example Output

3

#解析 :
 解析&&细节,见以下注释


AC代码 - - -

#solution1

import java.util.*;
import java.io.*;
public class Main {
    static int mxm = 1000005;
    static int tree[][] = new int[mxm][2],a[] = new int[mxm], mx;
    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    static int ini() throws IOException{
        int x=0,c=in.read(),f=1;while(c<48||c>57){if(c=='-')f=-1;c=in.read();}
        while(c>=48&&c<=57){x=(x<<3)+(x<<1)+(c^48);c=in.read();} return x*f;
    }
    
    static boolean dfs(int l, int r) {
        if(l==-1&&r==-1) return true;
        if(l==-1||r==-1) return false;
        if(a[l]!=a[r]) return false;
        mx+=2;
        return dfs(tree[l][0],tree[r][1])&&dfs(tree[l][1],tree[r][0]);
    }
    
    public static void main(String[] args) throws IOException {
        int n = ini(),t = 0, i = 0, ans = 1;
        for(i = 1; i <= n; ++i) {
            a[i] = ini();
        }
        for(i = 1; i <= n; ++i) {
            tree[i][0] = ini();
            tree[i][1] = ini();
        }
        for(i = 1; i <= n; ++i) {
            mx = 1;
            if(dfs(tree[i][0], tree[i][1])) {
                ans = Math.max(ans,mx);
            }
        }
        System.out.printf("%d\n", ans);
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值