|
Aleph-w 3.0
A C++ Library for Data Structures and Algorithms
|
Demonstrates BST balancing operation (recursive median selection with rotations) More...
#include <iostream>#include <fstream>#include <tclap/CmdLine.h>#include <aleph.H>#include <tpl_dynArray.H>#include <tpl_balanceXt.H>Go to the source code of this file.
Typedefs | |
| typedef BinNodeXt< int > | Node |
Functions | |
| void | print_keyb (Node *p, int, int) |
| void | print_keya (Node *p, int, int) |
| int | main (int argc, char *argv[]) |
Variables | |
| ofstream | outputb |
| ofstream | outputa |
Demonstrates BST balancing operation (recursive median selection with rotations)
This program demonstrates balance_tree() from tpl_balanceXt.H, which rebalances a BST by repeatedly selecting the median (by inorder position) and rotating it up to become the root, then recursing on the left and right subtrees.
It generates visualization files showing the transformation from an unbalanced BST to a size-balanced tree.
Unbalanced trees degrade to linked lists in worst case:
Balancing ensures:
The algorithm used in this example is:
n/2.In Aleph-w this is implemented by select_gotoup_root() + balance_tree().
The routine used here produces a size-balanced tree:
| Method | Time | Space | Result | Notes |
|---|---|---|---|---|
Median-rotations (balance_tree) | O(n log n) | O(1) | Size-balanced | Implemented by tpl_balanceXt.H |
| AVL | O(n log n) | O(log n) | Height-balanced | Maintains during ops |
| Red-Black | O(n log n) | O(log n) | Relaxed balance | Maintains during ops |
| Rebuild | O(n) | O(n) | Perfect | Requires extra memory |
balance-before-aux.Tree**: Original unbalanced tree (preorder)balance-after-aux.Tree**: Perfectly balanced tree (preorder)Both files can be visualized with btreepic tool to see the transformation.
Definition in file writeBalance.C.
Definition at line 187 of file writeBalance.C.
| int main | ( | int | argc, |
| char * | argv[] | ||
| ) |
Definition at line 203 of file writeBalance.C.
References Aleph::balance_tree(), Aleph::check_rank_tree(), Aleph::computeHeightRec(), Aleph::destroyRec(), Aleph::insert_by_key_xt(), log2(), Aleph::maps(), Aleph::BinNodeXt< Key >::NullPtr, outputa, outputb, Aleph::preOrderRec(), print_keya(), print_keyb(), root(), and Aleph::searchInBinTree().
| void print_keya | ( | Node * | p, |
| int | , | ||
| int | |||
| ) |
| void print_keyb | ( | Node * | p, |
| int | , | ||
| int | |||
| ) |
Definition at line 193 of file writeBalance.C.
References Aleph::BinNodeXt< Key >::get_key(), and outputb.
Referenced by main().
| ofstream outputa |
Definition at line 191 of file writeBalance.C.
Referenced by main(), and print_keya().
| ofstream outputb |
Definition at line 190 of file writeBalance.C.
Referenced by main(), and print_keyb().