static int res = 0; public static void main2(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[][] nums = new int[n][2]; for (int i = 0; i < n; i ++) { nums[i][0] = in.nextInt(); nums[i][1] = in.nextInt(); } isFUllTree2(nums, 1); System.out.println(res); } public static int[] isFUllTree2(int[][] nums, int root) { if (-1 == root) { return new int[] {0, 1}; // 走到了叶子结点时,高度为0,也是满树 } int[] left = isFUllTree2(nums, nums[root - 1][0]); // 递归的遍历左子树 int[] right = isFUllTree2(nums, nums[root - 1][1]); // 递归地遍历右子树 int curHeight = Math.max(left[0], right[0]) + 1; // 计算当前结点高度 if (left[0] == right[0] && 1 == left[1] && 1 == right[1]) { // 如果左右子树的高度相同且都是满树,则当前树也是满树 res++; return new int[] {curHeight, 1}; } else { return new int[] {curHeight, 0}; } }