gpt4 book ai didi

java - 空白ST : How to find the successor key given a key?

转载 作者:太空宇宙 更新时间:2023-11-04 12:45:57 25 4
gpt4 key购买 nike

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

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. 您需要一个私有(private)方法来获取 key 的Node
  2. 然后您获得该节点的后继节点并返回其值
  3. 您还应该更新“V get(K key)”方法以使用 getNode(K Key) 方法以避免代码重复

我已经编写了下面所有 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;
}

关于java - 空白ST : How to find the successor key given a key?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36323415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com