14public class AVLTree<Key
extends Comparable<Key>,Value>
15 extends BinarySearchTree<Key,Value> {
24 protected class AVLNode extends BinarySearchTree<Key,Value>.Node {
25 AVLNode(AVLTree<Key,Value> tree,Key key,Value value) {
26 super(tree,key,value);
35 return 1+(hl>hr ? hl : hr);
49 height_=1+(hl>hr ? hl : hr);
59 return -1<=b && b <=+1;
63 return getData().toString()+
" ("+height_+
")";
68 @Override
protected Node createNode(Key key,Value value) {
69 return new AVLNode(
this,key,value);
78 public int getHeight() {
return ((AVLNode)
head_).height_-1; }
80 @Override
protected void onInsert(Node _node) {
81 AVLNode node=(AVLNode) _node;
82 AVLNode parent=(AVLNode) node.getParent();
84 parent.updateHeight();
87 rebalance(node,parent,(AVLNode) parent.getParent());
90 protected void rebalance(AVLNode x,AVLNode y,AVLNode z) {
91 assert(x!=
null && x!=
head_);
93 assert(x.isBalanced());
94 assert(y==
head_ || y.isBalanced());
104 if (!z.isBalanced()) {
106 AVLNode b=(AVLNode) restructure(x);
107 AVLNode a=(AVLNode) b.getLeft();
108 AVLNode c=(AVLNode) b.getRight();
115 assert(b.isBalanced());
116 assert(a.isBalanced());
117 assert(c.isBalanced());
120 z=(AVLNode) b.getParent();
124 rebalance(y,z,(AVLNode) z.getParent());
134 @Override
public Value
remove(Key key) {
135 throw new UnsupportedOperationException(
"AVLTree#remove");
140 @Override
protected void checkConsistency(Node node) {
141 super.checkConsistency(node);
143 AVLNode anode=(AVLNode) node;
144 assert(anode.height_==anode.computeHeight());
145 assert(anode.isBalanced());
147 if (anode.height_!=anode.computeHeight())
148 throw new RuntimeException(
"imvalid height for node '"+anode+
"': "+
149 anode.height_+
"!="+anode.computeHeight());
150 if (!anode.isBalanced())
151 throw new RuntimeException(
"unbalanced node '"+anode+
"': balance="
152 +anode.getBalance());
156 public static void main(String[] args) {
158 AVLTree<String,Object> tree=
new AVLTree<String,Object> ();
159 System.out.println(tree);
161 String[] keys={
"c",
"b",
"a"};
163 for (String key : keys) {
164 System.out.println(
"insert '"+key+
"'");
165 tree.insert(key,
null);
166 System.out.println(tree);
167 System.out.println(tree.toText());
168 tree.checkConsistency();
boolean isBalanced()
|getBalance()|<=1 ?
int getBalance()
get height difference between left and right subtree
int getHeight(AVLNode node)
get height of subtree
int computeHeight()
compute height of subtree recursively (for testing only)