BinaryTree

Binary Trees
A binary tree is like a linked list but instead of keeping track of one element for every node, each node keeps track of two or more elements. This allows for fast sorting while adding elements to the tree. When an element is added to a two branched tree it is compared to the first item of the tree, or the root node. If it is 'less' than the root, then it is sent to the left and to the right otherwise. The process is then repeated until a vacant node is found. Going through multiple iterations of this will sometimes create very long branches and not very well balanced trees. This problem is tacked with AVL trees through rotations. A rotation is when an element in a binary tree is sent up the tree and swapped with another element to balance the tree. More on that here. Removing a node is even more interesting.

Now for a simple binary tree that sorts elements as they're added. code format="cpp"
 * 1) include
 * 2) include
 * 3) include

struct node{ string info; node *left, *right; node(string i){ info = i;       left = right = NULL; }   void print{ if(left != NULL) left->print; printf("%s\n", info); if(right != NULL) right->print; }   void add(node *n){ if(n->info < info){ if(left == NULL) left = n;           else left->add(n); }else{ if(right == NULL) right = n;           else right->add(n); }   } };

node *root;

int main{ root = new node("tyler"); root->add(new node("richard")); root->add(new node("tire")); root->add(new node("rick")); root->add(new node("trick"));

root->print; system("pause"); return 0; }

code