track操作类似与插入操作。
rank操作返回比当前元素小或者相等的元素数。
思路:track操作插入构造BST(没有保证平衡),但是节点增加一个leftSize,这里学习一下。
public class Solution { private static RankNode root = null; public static void track(int number) { if (root == null) { root = new RankNode(number); } else { root.insert(number); } } public static int getRankOfNumber(int number) { return root.getRank(number); } public static void main(String[] args) { track(20); track(15); track(25); track(10); track(23); track(5); track(13); track(24); System.out.println(getRankOfNumber(20)); System.out.println(getRankOfNumber(15)); System.out.println(getRankOfNumber(8)); } } class RankNode { int val; int leftSize; RankNode left; RankNode right; public RankNode(int v) { val = v; } public void insert(int t) { if (t <= val) { if (left != null) { left.insert(t); } else { left = new RankNode(t); } leftSize++; } else { if (right != null) { right.insert(t); } else { right = new RankNode(t); } } } public int getRank(int t) { if (t == val) { return leftSize; } else if (t < val) { if (left == null) return -1; else return left.getRank(t); } else { if (right == null) return -1; else { return right.getRank(t) + leftSize + 1; } } } }
时间: 2024-10-19 23:40:10