solution.java 1.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

public class _09BST插入节点问题 {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        int[] parent = new int[n];
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < n; i++) {
            parent[i] = sc.nextInt();
            map.put(i + 1, sc.nextInt());
        }
        ArrayList<Integer> childs = new ArrayList<Integer>();
        int rootWeight = map.get(1);
        int kWeight = map.get(k);
        for (int i = 0; i < parent.length; i++) {
            if (k == parent[i])
                childs.add(map.get(i + 1));
        }
        // 1.parents不存在的节点就是叶子节点,叶子节点的答案是无穷大
        if (childs.size() == 0) {
            System.out.println("叶子节点");
            System.out.println(-1);
            return;
        }
        // 2. 已经有左右孩子,答案是0
        else if (childs.size() == 2) {
            System.out.println("已经有左右孩子了");
            System.out.println(0);
            return;
        }
        // 3. 在右子树:k节点有左无右时为-1; 在左子树:k几点有右无左为-1
        else if (childs.size() == 1 && (kWeight > rootWeight && childs.get(0) < kWeight)
                || (kWeight < rootWeight && childs.get(0) > kWeight)) {
            System.out.println(-1);
            return;
        } else {
            int fatherWeight = map.get(parent[k - 1]);
            System.out.println(Math.abs(kWeight - fatherWeight) - 1);
            return;
        }
    }

}