输入样例
4
10 5
10 30
30 20
30 -1
输出样例
YES 2
我的问题是 在oj上关于NO的输出貌似都能通过 不能过的应该都是YES的部分 我不清楚我的代码里面是哪里除了问题
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class BST {
public static int[] readData() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// get the number of rows
int n = Integer.parseInt(br.readLine());
String[] strs;
int[] res = new int[2 * n];
for (int i = 1; i < n + 1; i++) {
strs = br.readLine().trim().split(" ");
//System.out.println(Arrays.toString(strs));
// read the left and right number of one row resp.
int parent = Integer.parseInt(strs[0]);
int child = Integer.parseInt(strs[1]);
// which means that there is no corresponding child, use 0 to denote null
if (child == -1) {
child = 0;
}
// read the second line with the same parent
if (res[i - 1] == parent) {
// put the child as the right child
res[2 * (i - 1) + 1] = child;
}
else {
res[i] = parent;
res[2 * i] = child;
}
}
br.close();
return res;
}
public static boolean isLeaf(int[] data, int index) {
// if the node is null, it is not a leaf
if (data[index] == 0) return false;
if (2 * index < data.length - 1) {
// the left and right children are both null
if (data[2 * index] == 0 && data[2 * index + 1] == 0) {
return true;
}
// the left and right children are not both null
else {
return false;
}
}
// 2 * index is out of bound
else {
return true;
}
}
public static int countLeaf(int[] data) {
int count = 0;
for (int i = 1; i < data.length; i++) {
// if the node is a leaf, count it
if (isLeaf(data, i)) count++;
}
return count;
}
public static boolean checkBSTprop(int[] data, int index) {
// no child can be found
if (2 * index >= data.length) {
return true;
}
// no child
if (data[2 * index] == 0 && data[2 * index + 1] == 0) {
return true;
}
// left child is 0, right child is nonzero
if (data[2 * index] == 0 && data[2 * index + 1] > data[index]) {
return true;
}
// right child is 0, left child is nonzero
if (data[2 * index + 1] == 0 && data[2 * index] < data[index]) {
return true;
}
// both children are nonzero
if (data[2 * index] < data[index] && data[2 * index + 1] > data[index]) {
return true;
}
// none of the conditions are satisfied
return false;
}
public static boolean isBST(int[] data) {
for (int i = 1; i < data.length; i++) {
if (!checkBSTprop(data, i)) {
return false;
}
}
return true;
}
public static void main(String[] args) throws IOException {
int[] res = readData();
int num = countLeaf(res);
/*
System.out.println(Arrays.toString(res));
System.out.println(countLeaf(res));
System.out.println(checkBSTprop(res, 1));
System.out.println(checkBSTprop(res, 2));
System.out.println(checkBSTprop(res, 3));
System.out.println(checkBSTprop(res, 6));
System.out.println(isBST(res));
*/
if (isBST(res)) {
System.out.println("YES " + num);
}
else {
System.out.println("NO");
}
}
}
代码里的balanceHeight函数可以帮助你