The binary lookup tree is a special one of the two-fork tree, it has a special property: for any node in the tree, all nodes of its left subtree are less than the keywords of this node, and all nodes of the right subtree are more than the key words of this node.
The special nature of the binary lookup tree makes it particularly convenient to find elements, and each lookup can remove half of the elements, so the time of the lookup is O (logn).
Binary lookup tree insertion and lookup algorithm is also very simple, that is, with the current node of the keyword comparison decision on the right or left to continue the operation.
Binary lookup tree The most complex algorithm is to delete the node algorithm, according to the node to be deleted two sub nodes or only one or no child nodes will have different processing. The general process of having two sub nodes is to find a node with the smallest value in the right subtree, replacing its value with the current node value. Then remove the node with the smallest value, which means that there are two sub nodes that replace the current node with the smallest node that is larger than the current node keyword (very awkward, I wish I had made it clear: in the case of only one or no child nodes, it is simpler to compare, and if there are child nodes on the position of the node to move up , and then delete the current node.
Implemented as follows:
1) BSTree.h
/**//********************************************************************
Created:2006/07/28
Filename:bstree.h
Author: Li Chong
http://www.cppblog.com/converse/
Purpose: Two fork lookup tree Implementation code
*********************************************************************/
#ifndef Binary_search_tree_h
#define Binary_search_tree_h
#include <stdio.h>
Template<typename t>
struct Btreenode
{
T Data;
btreenode* Pleft;
btreenode* Pright;
btreenode* pparent;
Btreenode (t data = t (), btreenode<t>* Parent = NULL,
Btreenode<t>* left = null, btreenode<t>* right = null)
: Data (data), Pleft (left), Pright (right), pparent (Parent)
{
}
};
Template<typename t>
Class Bstree
{
Protected
btreenode<t>* M_prootnode;
Public
Bstree (btreenode<t>* proot = NULL)
: M_prootnode (Proot)
{
}
~bstree ();
void Display ();
btreenode<t>* Insert (const t& data);
btreenode<t>* Find (const t& data);
btreenode<t>* findmin ();
btreenode<t>* Findmax ();
btreenode<t>* Delete (const t& data);
Private
void Display (btreenode<t>* p);
btreenode<t>* Insert (const t& data, btreenode<t>* p);
btreenode<t>* Find (const t& data, btreenode<t>* p);
btreenode<t>* findmin (btreenode<t>* p);
btreenode<t>* Findmax (btreenode<t>* p);
btreenode<t>* Delete (const t& data, btreenode<t>* p);
void Destructimpl (btreenode<t>* p);
};
#endif