15 #include "tools/GenericException.h"
16 #include "tools/AutoFilePtr.h"
18 template<
class Item>
const char* toString(
const Item& i);
19 template<
class Item>
int sort_compare(
const Item& i1,
const Item& i2);
58 template<
class Item>
int sort_compare(
const Item& a,
const Item& b);
75 void add(
const Item &item)
114 void traverse(
void (*visit) (
const Item &,
void *),
void *arg=0)
115 { visit_inorder (visit, root, arg); }
133 {
return check_balance(root); }
136 PROHIBIT_DEFAULT_COPY(
AVLTree);
141 if ((*node)->left->balance == 1)
142 rotate_left(&(*node)->left);
150 (*node)->balance += 1;
152 if ((*node)->balance == 1)
161 if ((*node)->right->balance == -1)
162 rotate_right(&(*node)->right);
170 (*node)->balance -= 1;
172 if ((*node)->balance == -1)
190 (*node)->item = new_node->
item;
196 if (insert(new_node, & ((*node)->left)))
199 if ((*node)->balance < -1)
204 return (*node)->balance < 0;
209 if (insert(new_node, & ((*node)->right)))
212 if ((*node)->balance > 1)
217 return (*node)->balance > 0;
223 void visit_inorder(
void (*visit) (
const Item &,
void *),
228 visit_inorder(visit, node->
left, arg);
229 visit(node->
item, arg);
230 visit_inorder(visit, node->
right, arg);
238 fprintf(f,
"n%d [ label=\"%s (%d)\" ];\n",
242 fprintf(f,
"n%d -> n%d\n", me, i+1);
243 print_dot_node(f, node->
left, i);
247 fprintf(f,
"n%d -> n%d\n", me, i+1);
248 print_dot_node(f, node->
right, i);
257 cleanup(node->
right);
266 int l = height(node->
left)+1;
267 int r = height(node->
right)+1;
268 return (l>r) ? l : r;
281 height(node->
right) - height(node->
left))
283 return check_balance(node->
left) &&
284 check_balance(node->
right);
293 sprintf(filename,
"%s.dot", name);
299 fprintf(f,
"# dot -Tpng %s.dot -o %s.png && eog %s.png\n",
302 fprintf(f,
"digraph AVLTree\n");
305 print_dot_node(f, root, i);
void clear()
Delete all tree entries.
Definition: AVLTree.h:118
bool find(Item &item)
Try to find item in tree.
Definition: AVLTree.h:93
AVL-type balanced tree.
Definition: AVLTree.h:64
Auto-close FILE pointer wrapper.
Definition: AutoFilePtr.h:15
short balance
balance
Definition: AVLTree.h:45
Item item
item
Definition: AVLTree.h:36
AVL tree item.
Definition: AVLTree.h:26
AVLItem * left
Left pointer.
Definition: AVLTree.h:39
bool selftest()
Tests if the tree is AVL-balanced.
Definition: AVLTree.h:132
AVLItem(const Item &i)
Constructor.
Definition: AVLTree.h:31
Generic Exception: Base class for exceptions.
Definition: GenericException.h:45
void traverse(void(*visit)(const Item &, void *), void *arg=0)
Sorted (inorder) traverse, calling visitor routine on each item.
Definition: AVLTree.h:114
AVLItem * right
Right pointer.
Definition: AVLTree.h:42
void add(const Item &item)
Add (copy) Item into the tree.
Definition: AVLTree.h:75