Binary search Tree

Source: Internet
Author: User

definitionBinary search tree, or binary lookup tree, also known as a binary sort tree, is called Two forks

It is either an empty tree or a two-fork tree with the following properties:

    1. If the left subtree is not empty. The value of all nodes on the left subtree is less than the value of its root node;
    2. If the right sub-tree is not empty. The value of all nodes on the right subtree is greater than the value of its root node;
    3. The left and right sub-trees are also two-fork search trees respectively.
Propertiestwo fork search tree compared to ordinary binary tree. Have some excellent features or properties:
    1. Because the nodes are discharged sequentially: Left dial hand tree < root node < right subtree.

      It is the time to find a node. It is only necessary to compare with the root node before deciding whether to go to the left subtree or the right sub-tree. And the ordinary binary tree needs to traverse one after another.

    2. The time complexity of finding, inserting is O (h), and H is the height of the tree. That is, when the height of the tree is as low as possible (more balanced), the efficiency is high.

Algorithmic InterpretationIt must be said that the operation of nonlinear structures is really difficult to linear structure, some algorithms are more complex logic.

The following is an explanation of some of the algorithms given in the code for easy reading.

  1. Construction Method: Binarysearchtree (); The process of achievement is an insertion process. So the insert operation is important.
  2. To find the number of leaf nodes: int leaf (); traverse the tree in some way, if the left and right children are empty. That is the leaf node. The code is traversed in the middle order.
  3. Find specified node: bool Search (elemtype); Based on the distribution characteristics of binary search tree nodes, find only needs to be done in the left or right sub-tree. The insertion of nodes that are already in the tree is also unsuccessful. The insert operation logic is clearer and the code is easy to read.

  4. gets the predecessor of the specified node: btnode* predecessor (Elemtype); This operation is not in the normal binary tree. In binary search tree, the precursor of a node refers to the precursor of the middle sequence traversal. Therefore, this operation is essentially a middle-order traversal process.

    Slightly different, it is necessary to log the node plastvisit of the most recent traversal during traversal, and infer whether the currently visited node is a specified node. If so, then return to plastvisit.

  5. The same is true for the acquisition of successors and the acquisition of precursors.

  6. Get minimum node: btnode* minimum (); The smallest node in the binary search tree must be in Zuozi (assuming it exists).

    So, constantly traversing the left subtree can be. Simpler.

  7. Get maximum node: btnode* maximum (); two forks the maximum node in the search tree must be in the right subtree (assuming it exists). As a result, it is easier to traverse the right sub-tree continuously.
  8. Insert node: bool Insertnode (elemtype); the process of inserting is essentially a lookup, and it is necessary to remember that the new node is inserted into the leaf node.

  9. Traversal: void traverse (); The traversal of the binary search tree can be varied, and various traversal methods are also implemented in the previous two-fork tree, where only the middle sequence traversal is given. As a result, the sequential traversal of a binary search tree results in a sort sequence of nodes from small to large.
  10. Delete node: bool Deletenode (elemtype); The rule to delete is this:
    • If there is no left subtree for the truncated point, replace it with the root node of its right sub-tree.
    • If there is a left dial hand tree to be truncated, look for the last node in the left subtree for the middle order traversal, replacing it with that node.


The deletion rule is better understood. But detailed implementation, the details are numerous, very not easy.

This is also the most complex of all operations. Drawing comprehension:
Other operations have been explained in the previous two fork tree. Don't dwell on it.

Detailed details have to look at the code, the code is longer, it is recommended to understand the method as a unit. Code class definition

 #include <iostream># include<iomanip> #include <stack> #include <queue>using namespace Std;typedef int elemtype;// Binary tree node class Btnode//binary tree node{public:elemtype data;   btnode* Lchild;   Left child btnode* Rchild; Right child Btnode (Elemtype D, btnode* left = null, btnode* r = null):d ata (d), Lchild (left), Rchild (right) {}};//Two forks search tree class Bi narysearchtree{private://root btnode* root;//total number of nodes int size;public://construction method Binarysearchtree ();//destructor Method ~binarysearchtree () ;//inference tree null bool Empty () {return Root = NULL;} Total number of nodes int getsize () {return size;} The leaf node number int leaf ();//find bool Search (elemtype);//Get parent node btnode* (elemtype);//Get precursor btnode* predecessor (ELEMTYPE); /Get successor btnode* successor (ELEMTYPE);//Gets the minimum node btnode* minimum ();//Gets the maximum node btnode* maximum ();//Insert new node bool Insertnode ( Elemtype);//Delete node bool Deletenode (elemtype);//middle sequence traversal void traverse () {inorderwithoutrecursion ();} void Inorderwithoutrecursion ();}; 
class Implementation

Construction Method Binarysearchtree::binarysearchtree () {size = 0; Root = NULL; Elemtype data;cout << "Achievements, input node, input 0 end:"; while (CIN >> data && data) insertnode (data);} The Destructor method Binarysearchtree::~binarysearchtree () {if (!empty ()) {queue<btnode*> Q;q.push (Root); btnode* p = null;while (!q.empty ()) {p = Q.front (); Q.pop ();//The Left child is not empty. Then the left child is enqueued if (p->lchild) Q.push (p->lchild);//Right child is not empty. Then the right child is enqueued if (p->rchild) Q.push (p->rchild);//free memory delete p;}}} Find the number of leaf nodes int binarysearchtree::leaf () {int num = 0;//to traverse if (!empty ()) {stack<btnode*> s by the middle order; btnode* p = root;while (!s.empty () | | p) {if (p) {S.push (p);p = P->lchild;} Else{p = S.top (); S.pop ();//left and right subtree are empty, then leaf node if (p->lchild = = NULL && P->rchild = null) num++;p = p->rchild; }}}return num;} find bool Binarysearchtree::search (Elemtype data) {if (!empty ()) {btnode* p = root;while (p) {if (data = = P->data) return t Rue;else if (Data < p->data) p = p->lchild;elsep = P->rchild;}} Tree empty or lookup failed return false;} btnode* Binarysearchtree::p arent (Elemtype data) {if (!empty ()) {////The parent node of the root node is empty if (root->data = = data) return null;stack<btnode*> s; btnode* p = root;while (!s.empty () | | p) {if (p) {S.push (p);p = P->lchild;} After visiting the else{//left dial hand tree, visit right subtree P = s.top (); S.pop (); if (p->lchild && p->lchild->data = data) | | (p->rchild && P->rchild->data = = data)) return p;p = P->rchild;}}} return NULL;} Get precursor btnode* binarysearchtree::p redecessor (elemtype data) {btnode* pcur, *plastvisit;pcur = Plastvisit = NULL;if (! Empty ()) {stack<btnode*> s;pcur = Root;while (!s.empty () | | pcur) {if (pcur) {//plastvisit = Pcur;s.push (pcur);p cur = Pcur->lchild;} Else{pcur = S.top (); S.pop (); if (pcur->data = = data) return plastvisit;elseplastvisit = Pcur;pcur = Pcur->rchild;}}} return plastvisit;} Get successor btnode* Binarysearchtree::successor (elemtype data) {btnode* pcur = Null;pcur = Root;if (!empty ()) {Stack<BTNode *> S;while (!s.empty () | | pcur) {if (pcur) {s.push (pcur);p cur = pcur->lchild;} Else{pcur = S.top (); S.pop (); if (Pcur->data = = data) return pcur->rchild;pcur = Pcur->rchild;}} Empty tree return null;} Gets the minimum node btnode* binarysearchtree::minimum () {//min node at Zuozi bottom if (!empty ()) {btnode* p = root;while (p->lchild) p = p-> Lchild;return p;} tree empty return null;} Gets the maximum node btnode* binarysearchtree::maximum () {///MAX node at the right subtree bottom if (!empty ()) {btnode* p = root;while (p->rchild) p = p-> Rchild;return p;} tree empty return null;} Insert new node bool Binarysearchtree::insertnode (Elemtype data) {/* new node will be inserted into the leaf insert generally does not fail unless the node is inserted repeatedly. */if (root = NULL) {root = new Btnode (data); Size++;return true;} else{btnode* p = Root;while (True) {if (Data < P->data) {//Left dial hand tree is assumed. Then continue traversing the left subtree if (p->lchild) p = p->lchild;else{//Otherwise, insert node, same as P->lchild = new Btnode (data); else if (Data > P->data) {if (p->rchild) p = p->rchild;else{p->rchild = new Btnode (data); break;}} Else//encountered repeated node return false;} Insert new node successfully, total number of nodes plus one Size++;return true;}} Delete node bool Binarysearchtree::d eletenode (elemtype data) {/* Delete rule 1. If there is no left subtree for the deletion point, replace it with the root node of its right subtree.

2. If there is a left dial hand tree to be truncated, look in the left subtree for the last node in the middle order traversal, replacing it with that node.

*/if (!empty ()) {//tree does not have this node. Delete Failed if (!search (data)) return False;/*p: The parent of the node to be deleted: Parents of nodes to be removed temp: Replacement node Tempp, parent node of replacement node */btnode* p, *parent, *temp, * tempp;p = parent = Temp = TEMPP = null;//Gets the parent node of the node to be deleted parent = parent (data);//Based on parent node. Determine which node to delete if (parent->lchild && parent->lchild->data = = data) p = Parent->lchild;elsep = parent-> rchild;//assuming that the left subtree is not empty, find the last node in the sequence traversal if (p->lchild) {temp = P->lchild;while (temp->rchild) {tempp = temp;// Constantly traversing right subtree temp = temp->rchild;} Suppose P's left child is the replacement node if (tempp = = NULL) P->lchild = temp->lchild;else//The left subtree of the replacement node as the right subtree of its parent node (this sentence is difficult to understand, need to think more about) tempp-> rchild = temp->lchild;//Replacement node inherits left and right child Temp->lchild = P->lchild;temp->rchild = P->rchild;} elsetemp = p->rchild;//Replace node (this is also why it is necessary to find the parent node of the delete node) if (parented = NULL)//The node to be deleted is just the root, and temp;else if (parent->). Lchild = = p)//To delete the node itself in the left sub-tree Parent->lchild = temp;else//to delete the node itself in the right subtree Parent->rchild = temp;//Delete the node to be deleted delete p;// Total number of nodes minus one size--;return true;} Tree empty return false;} Middle sequence traversal void binarysearchtree::inOrderwithoutrecursion () {if (!empty ()) {stack<btnode*> s; btnode* p = root;while (!s.empty () | | p) {if (p) {S.push (p);p = P->lchild;} Else{p = S.top (); S.pop () cout << SETW (4) << p->data;p = P->rchild;}} cout << Endl;}}

Main function

int main () {cout << "****** two-fork search tree ***by david***" << Endl; Binarysearchtree tree;cout << "Middle sequence Traversal" << endl;tree.traverse () cout << total number of nodes in Tree << tree.getsize () << endl;cout << leaf node number << tree.leaf () << Endl; btnode* p = null;p = Tree.minimum ();p? cout << "Minimum node is" << p->data << endl:cout << "tree empty. "<< endl;p = Tree.maximum ();p? cout << "Max node is" << p->data << endl:cout << "tree empty. "<< Endl;  Elemtype data = 2;cout << endl << "Find node" << data << endl;if (Tree.search (data) {cout << "node) "<< data <<" found success!

"<< endl;p = tree.predecessor (data);p?

The precursor of

cout << node << data << is "<< p->data << endl:cout <<" no precursor! "<< endl;p = tree.successor (data);p? cout << "Node" << data << "The successor is" << p->data << endl:cout << "no successor! "<< Endl;} Elsecout << "Node" << data << "Not in the tree!" "<< endl;data = 6;cout << endl <<" Delete node "<< data << endl;if (Tree.deletenode (data) {cout &L t;< "deleted successfully! << endl;cout << Middle order Traversal << endl;tree.traverse (); cout << total nodes in tree << tree.getsize () << ; Endl;cout << leaf nodes << tree.leaf () << endl;data = 5;cout << endl << "Find nodes" << data << endl;if (data) {cout << node << data << "Find successful!"

"<< endl;p = tree.predecessor (data);p? cout << "Node" << data << "The precursor is" << p->data << endl:cout << "no precursor! "<< endl;p = tree.successor (data);p? cout << "Node" << data << "The successor is" << p->data << endl:cout << "no successor! "<< Endl;} Elsecout << "Node" << data << "Not in the tree!" "<< Endl;} Elsecout << "Delete failed! "<< endl;cout << endl;system (" pause "); return 0;}

Execution



algorithm Optimizationan optimized version number for the insertion algorithm
Insert new node bool Binarysearchtree::insertnode (Elemtype data) {Btnode *parent, *child;parent = Null;child = Root;while (Child) {parent = child;if (Data < child->data) Child = Child->lchild;else if (Data > Child->data) child = child-> rchild;else//Insert the same keyword node. Returns Falsereturn false;} At this point the parent is either empty or the leaf node if (parent = = NULL)//empty tree root = new Btnode (data), else if (Data < Parent->data) parent-> Lchild = new Btnode (data), Elseparent->rchild = new Btnode (data); Size++;return true;}

full code Download: Two Forks search tree    if help, the top one Oh!


Columns folder:

  • Data structure and algorithm folders
  • C pointer


Copyright notice: This article Bo Master original article. Reproduced, reproduced please indicate the source.

Binary search Tree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.