我如下构建一个简单的AVL树,每个节点都有键和值.现在,我想实现一个方法,该方法可以返回具有最大值的节点的键.例如,如果我有一棵像这样的树:
(7,1)
/ \
(4,3) (13,8)
/ \ / \
(2,4) (6,3) (11,8) (15,2)
/ \ / / \ / \
(1,9)(3,0)(5,16)(9,2)(12,3)(14,3)(16,5)
/ \
(8,19)(10,4)
该方法将返回8,因为节点(8,19)具有最大值.以下是我的avl树和节点构造函数.我确实尝试手动实现此方法,但不知何故.如果有人可以帮助我,我将不胜感激.
public class AVLTreeImp,V> implements AVLTree{
private Node root;
public class Node,V> implements AVLTree.Node{
T key;
V value;
Node left;
Node right;
Node parent;
int height;
public Node(){
this.key = null;
this.left = null;
this.right = null;
this.parent = null;
this.height = 0;
this.value = null;
}
public Node(T key, V value, Node left, Node right){
this.key = key;
this.left = left;
this.right = right;
this.parent = null;
this.height = 0;
this.value = value;
}
}
public AVLTreeImp(){
this.root = null;
}
@Override
public void insert(T key, V value){
root = insert(root,key,value);
}
private Node insert(Node node, T key, V value){
if (node == null){
node = new Node(key, value,null,null);
}else{
if (key.compareTo(node.key) < 0){
node.left = insert(node.left, key, value);
if (!(isBalanced(node))) {
if (key.compareTo(node.left.key) < 0) {
node = leftLeftRotation(node);
} else {
node = leftRightRotation(node);
}
}
}else if (key.compareTo(node.key) > 0){
node.right = insert(node.right,key,value);
if (!(isBalanced(node))){
if (key.compareTo(node.right.key) > 0){
node = rightRightRotation(node);
}else{
node = rightLeftRotation(node);
}
}
}
}
regenerateHeight(node);
return node;
}
下面是我对这种方法的实现,我不确定这是怎么回事.
public Integer findMax(){
Node result = (Node)root;
result.value = 0;
return findMax((Node) root,result);
}
private Integer findMax(Node node,Node result){
if (node == null){
return result.key;
}
if (node.value > result.value ||
(node.value == result.value && node.key.compareTo(result.key) < 0)){
result = node;
}
findMax(node.left,result);
findMax(node.right,result);
return result.key;
}