BST:如何找到钥匙的后继钥匙?

时间:2016-03-31 03:06:45

标签: java parent-child binary-search-tree nodes

我正在使用BST。给定一个密钥,我将如何找到后继密钥?这是我到目前为止的代码。我设法插入一个新密钥并检索给定密钥的值。现在,我需要完成下一个方法。我该如何处理?

class BST<K extends Comparable<K>, V> implements RangeMap<K,V> {
class Node {
    Node left;
    Node right;
    Node parent;
    KVPair<K,V> kv;
    K key;
    V value;
    public Node(K key, V value) {
        this.key = key;
        this.value = value;
        parent = left = right = sentinel;
    }
}

private Node root;


public void add(K key, V value) {
    // TODO: Implement me(basic score)
    root = add (root, key, value);
}

private Node add(Node x, K key, V value){
    if (x == null){
        return new Node(key, value); }
        int cmp = key.compareTo(x.key);
        if (cmp < 0){
            x.left = add(x.left, key, value);}
            else if (cmp > 0 ){
                x.right = add(x.right, key, value);}
                else if (cmp == 0){
                    x.value = value;} 
    return x;
}


public V get(K key) {
    Node x = root;
    while (x != null){
        int cmp = key.compareTo(x.key);
        if (cmp < 0){
            x = x.left;}
            else if (cmp > 0 ){
                x = x.right;}
               else if (cmp == 0){
                   return x.value;}
      }
    return null;
}


public K next(K key) {

1 个答案:

答案 0 :(得分:0)

  1. 您需要一个私有方法来获取密钥
  2. 的节点
  3. 然后您获得该节点的后继并返回其值
  4. 您还应该更新您的&#34; V get(K键)&#34;使用getNode(K Key)方法避免代码重复的方法
  5. 我已经写了以下所有3种方法

        private Node getNode(K key) {
            Node x = root;
            while (x != null){
                int cmp = key.compareTo(x.key);
                if (cmp < 0){
                    x = x.left;
                } else if (cmp > 0 ) {
                    x = x.right;
                } else if (cmp == 0){
                    return x;
                }
              }
            return null;
        }
    
        public K next(K key) {
            Node x = getNode(key);
            if (x.right != null) {
                x = x.right;
                while (x.left != null) {
                    x = x.left;
                }
                return x.key;
            }
            Node p = x.parent;
            while (p != null && p.right == x) {
                p = p.parent;
                x = x.parent;
            }
            return p.key;
        }
    
        public V get(K key) {
            Node x = getNode(key);
            return x==null?null:x.value;
        }       
    
相关问题