Building a binary tree using C + +

Source: Internet
Author: User

The binary tree was a fundamental data structure used in computer. The binary tree was a useful data structure for rapidly storing sorted data and rapidly retrieving

Stored data. A binary tree are composed of parent nodes, or leaves, each of which stores data and also Des (leaves) which can be visualized

Spatially as below the "I" and "one placed to" to "right." It is the relationship between the leaves linked to and the linking leaf, also know

N as the parent node, which makes the binary tree such a efficient data structure. It is the leaf on the left which has a lesser key value (i.e., the value used to search for a Le

AF in the tree), and it's the leaf on the right which has a equal or greater key value. As a result, the leaves on the "farthest left of the" tree have the lowest values, whereas th

E leaves on the right of the have the greatest values. More importantly, as each leaf connects to two leaves, it is the beginning of a new, smaller, binary. Due

To that nature, it's possible to easily access and insert data in a binary tree using search and insert functions Recursi Vely called on successive leaves.

Binary tree is a kind of basic data structure in computer science. It is a very useful data structure for fast storage and fast traversal of ordered data. A binary tree consists of a parent node or a cotyledons, each of which is stored with data and connected to two other nodes (leaves), so that the structure is visually manifested as having a position on the left node under the first node and a location for the right node, Is the relationship between the connected node (cotyledons) and the node (parent node) to which the other node is connected. This makes the binary tree an efficient data structure. The leaf values on the left side of the binary tree always hold a small value, while the leaves on the right always hold a larger value. So, on the left, the bottom tree

The value of the leaf is the smallest, whereas the bottom leaf of the right is the largest. Most importantly, each node connected to the other two nodes is the beginning root node of a new binary tree, which enables the use of search and insert functions to recursively

Easy access to each leaf of the binary tree and inserting data into the two fork tree becomes possible.

The typical graphical representation of a binary is essentially to that of. It begins with a root node, which contains the original key value. The root

Node has two child nodes; Each child node might have it own child nodes. Ideally, the tree would being structured so, it's a perfectly balanced tree, and each node

Having the same number of the child nodes to the A perfectly balanced tree allows for the fastest average insertion of data or retrieval of. The worst case

Scenario is a which each node only has one child node and so it becomes as if it were a linked list in terms of speed . The typical representation of a binary tree looks

Like the following:

The most typical graphical representation of a binary tree is an inverted tree, starting with the root node with a key value. The root node has two child nodes, each child node may have its own child node, ideally, this tree will be constructed into a fully balanced binary tree, each left and right child nodes have an equal number of child nodes. Fully balanced binary trees can be inserted into the data and traverse the data has the smallest average time complexity, the worst case is that each node only

A child node, which allows the tree to have the same structure as the linked list, and the following is a graphical representation of a typical binary tree:

10
/    \
6 14
/  \     /   \
5 8 11 18

The node storing the "represented here merely as", is the root node, linking to the "left" and right child nodes, with The left node storing a lower value than the parent node, and the node on the right storing a greater value than the Paren T node. Notice that if one removed the root node and the right child nodes, the node storing the

Value 6 would is the equivalent a new, smaller, binary tree.

A node holding a value of 10 is simple here with 10, he is the node of the whole tree, connected to a left subtree and a right subtree, Zuozi save the number of its parent node, the right subtree save than its parent node large number. Note that if we remove the root node and the right subtree, then the node storing 6 will be the root of a new, smaller tree.

The structure of a binary tree makes the insertion and search functions simple to implement using recursion. In fact, the two insertion and search functions are also both very. To insert data into a binary tree involves a function searching for a unused node in the proper position in the Hich to insert the key value. The Insert

function is generally a recursive function that continues moving down the levels of a binary tree until there are an unused Leaf in a position which follows the rules of

Placing nodes. The rules are that a lower value should is to the left of the node, and a greater or equal value should is to the right. Following the rules, an insert function

Should check each node to = if it is empty, if so, it would inserts the data to being stored along with the key value (in MO St implementations, an empty node would simply be a

NULL pointer from a parent node, so the function would also have to create the node. If the node is filled already, the Insert function should check to the if the key value

To being inserted is less than the key value of the ' current node, ' and if so ', the Insert function should be recursively called On the left child node, or if the key value to is inserted

is greater than or equal to the key value of the ' current node ' Insert function should be recursively on the called T child node.

The structure of the binary tree makes inserting and finding simple recursion can be achieved, in fact, insert operation and search is very similar, when the binary tree to insert data, it involves to query a node in the correct location and not used before inserting the value. An insert function is a recursive function that constantly moves to the following node in the specified rule until it finds a node in the correct location that is not being used, and its principle of movement is: compared to a node

A smaller value should be placed on the left child node of the modified node, greater than or equal to the child node. According to this principle, the Insert function should check whether each node is empty, and if it is empty, the storage of the inserted value should be accompanied by a new section

Point, (in most code implementations, the null node is represented by a null pointer, so the INSERT function needs to create a new node). If a node has been found with an exact value, the insertion function should determine whether the newly inserted value is

is smaller than the value on the current node, if the new value teaches small, then the function recursively calls the function to access the child nodes of the current node; If the new value is greater than or equal to the current node's value, it should be recursive to the right subtree, straight

To find a suitable location and insert.

The search function works along a similar fashion. It should check to the if the key value of the ' current ' node is the ' searched. If not, it should check to the if the the value to be searched the ' is less than the value of the ' node, in which case it Shoul D be recursively called on the left child node, or if it's greater than the value of the node, it should be recursively Called on the right child node. Of course, it is also necessary to check to ensure which the left or right child node actually exists the before the

function on the node.

The search function is similar to the Insert function, it determines whether the current node's value is consistent with the value to search for, and if it is inconsistent, the value of the search is smaller than the value of the current node, and if it is, the value of accessing the left node continues to contrast, otherwise the value of the right Of course, the next left and right child nodes that are checked and guaranteed access in recursion are present.


Because binary trees have log (base 2) n layers, the average search time for a binary of the tree is log (base 2) n. To fill a entire binary tree, sorted, takes roughly log (base 2)

n * N. Let's take a look at the "necessary code for" A simple implementation of a binary tree. The It is necessary to have a struct, or class, defined as a node.

Because the binary tree has log (base 2) n layer, the average time complexity of the search is log (base 2) n. Filling an entire ordered two-fork tree the approximate time complexity is log (base 2) n * N. Let's take a look at the core code that implements a binary tree, and first, you should construct a struct, or a class, defined as node:

struct node
{
  	int key_value;  
  	Node *left;  
  	Node *right;
};

The struct has the ability to store the Key_value and contains the two child nodes which define the "node as part of" tree . In fact, the node itself are very similar to the node in a linked list. A basic knowledge of the code for a linked list is very helpful in understanding the techniques of binary. Essentially, pointers are necessary to

Allow the arbitrary creation of the new nodes in the tree.

The defined structure body should be able to store the key value of the node and contain two child nodes defined as part of the tree. In fact, the node itself is very similar to the node of the linked list. The basic knowledge of the linked list is very helpful for understanding the binary tree, and the setting of the pointer is necessary in order to be able to create an idea number of nodes to the tree.


It is most logical to create a binary tree class to encapsulate the workings of the "the Tree" into a, and also maki NG IT reusable. The class would contain functions to

Insert data into the "tree" and "search for data." Due to the "use of" pointers, it'll be necessary to include a function to delete the ' tree ' in order to conserve memory afte R the

Program has finished.

Creating a binary tree class to encapsulate the operating room of a tree is most logical. and make it reusable at the same time. You should include insert functions and search functions in your class, because you use a pointer to use the DELETE function to free up memory after the program finishes working.

Class Btree
{public
:        
	btree ();        
	~btree ();        
	void Insert (int key);       
	Node *search (int key);        
	void Destroy_tree ();    
Private:        
	void Destroy_tree (node *leaf);        
	void Insert (int key, node *leaf);        
	Node *search (int key, node *leaf);                
	Node *root;
};

The insert and search functions that are public members of the class are designed to allow the user of the class to use th E class without dealing with the underlying

Design. The insert and search functions which would be called recursively are the ones which contain two, parameters allowing To travel down the tree. The

Destroy_tree function without arguments is a front for the Destroy_tree function which to recursively the tree,  Node by node, from the bottom up. The code for the class would look similar to the following:

The Insert function and the search function are set to the public method in the class, so that the users of the class can use the functionality better. Insert functions and search functions with two parameters will be called recursively to enable access to the tree from top to bottom. The Destroy_tree function with no parameters is the previous step of the call to Destroy_tree, with the parameter Destroy_tree function to delete recursively from the bottom node to one of the nodes. The code is as follows:

Btree::btree ()
{
	root=null;
}

It is necessary to initialize root to NULL for the later functions to being able to, to recognize this it does not exist.


Initializing root is null so that the following function is necessary to determine that the root is no longer present.

Btree::~btree ()
{  
	destroy_tree ();
}

The Destroy_tree function would set off the recursive function destroy_tree shown below which'll actually delete all node s of the tree.


The Destroy_tree function is used to trigger the following recursive function Destroy_tree to delete every node in the tree

void Btree::d estroy_tree (node *leaf)
{
<span style= "White-space:pre" >	</span>if (leaf!= NULL)
  <span style= "White-space:pre" >	</span>{
 <span style= "White-space:pre" >		</span>destroy_tree (leaf->left);
   <span style= "White-space:pre" >		</span>destroy_tree (leaf->right);
<span style= "White-space:pre" >		</span>delete leaf;
<span style= "White-space:pre" >	</span>}

The function Destroy_tree goes to the bottom of the "the Tree", which is, searching while there is a non-null node, Deletes that leaf, and then it's way back up. The function deletes the leftmost node, then the right child node from the leftmost node ' s parent node, then it deletes th E parent node, and it continues this deletion

Working its way the "node of the" tree upon which Delete_tree is originally called. In the example tree above, the order of deletion of nodes would to be

5 8 6 11 18 14 10. Note This it is necessary to delete all the child nodes to avoid wasting memory.

The Destroy_tree function goes from the bottom of the tree through each part of the tree to the top of the tree. That is, searching for each non-empty node deletes the node, and then the function returns to a layer, which deletes the leftmost node and then deletes it.

The parent node of the leftmost node, then deletes the parent node, and then continues to delete another node under the same parent node in the same way, and then deletes the parent node until the node is finally deleted, as in the example

The deletion order of the numbers is 5 8 6 11 18 14 10. Remove every node in the tree to prevent waste of memory

void btree::insert (int key, node *leaf) {if (key< leaf->key_value) {if (leaf->left!=null
    ) Insert (key, leaf->left);
      else {leaf->left=new node;
      leaf->left->key_value=key;    leaf->left->left=null;   Sets the "Child of the" child node to null leaf->left->right=null; Sets the right child of the child node to null}} else if (key>=leaf->key_value) {if Leaf->rig
    ht!=null) Insert (key, leaf->right);
      else {leaf->right=new node;
      leaf->right->key_value=key;  leaf->right->left=null; Sets the "Child of the" child node to null leaf->right->right=null; Sets the right child's child node to null}} 

The case where the "root" node is still NULL would be taken care of by the Insert function, which nonrecursive and availabl E to Non-members of the class. The Insert function searches, moving down the tree of children nodes, following the prescribed rules, left for a lower Val UE to is inserted and right for a greater value, until it finds a empty

node which it creates using the ' new ' keyword and initializes with the key value while setting the new node ' s child node p Ointers to NULL. After creating the new node,

The Insert function would no longer call itself.

If the root node is null, the Insert function will take into account that it is not recursive and is valid for classes that are not members. When the Insert (with parameters) function looks down on no nodes, follow the rule described earlier

-----Insert a small value on the left and a large value on the right until it finds an empty node, create a new node to save the key value and set the child section to point to NULL, and then insert into the empty node, the Insert function stops recursion.

Node *btree::search (int key, node *leaf)
{
  if (leaf!=null)
  {
    if (key==leaf->key_value)
      return leaf;
    if (key<leaf->key_value) return
      search (key, leaf->left);
    else return
      search (key, leaf->right);
  }
  else return NULL;
}

The search function shown above recursively moves down the "tree" until it either reaches a node with a key value equal to T He value for which the function is searching or until the function reaches a uninitialized node, meaning that the value B Eing searched for isn't stored in the binary tree. It returns a pointer to the node to the previous

instance of the function which called it, handing the pointer back up to the search function accessible outside the class.

The search function recursively searches the tree down from the node until it finds a value that is the same as the target value, or encounters a node that is not initialized, meaning that there is no target value to query in the tree. function to return a pointer to a node to the previous instance object to invoke its function, and handling the search function returned by the pointer in the class is feasible.

void Btree::insert (int key)
{
  if (root!=null)
    Insert (key, root);
  else
  {
    root=new node;
    root->key_value=key;
    root->left=null;
    root->right=null;
  }
}

The public version of the Insert function takes care to the case where the root has not been initialized by allocating the Memory for it and setting both, the nodes to NULL and setting of the Key_value to the. If the root node already exists, insert is called with the root node as the initial node of the function, and the Recursiv E

Insert function takes over.

The public Insert function creates memory for the root node when it finds null and sets its two child nodes to null and inserts the key value into the root node, and if the root node already exists, the Insert function takes the root node

The initial node of this function recursively calls insert to insert the node.

Node *btree::search (int key)
{return
  search (key, root);
}

The public version of the "search function is used" to "set off" search recursion at the root node, keeping it from being necessary for the user to have access to the root

Node.

The purpose of the public function search is to initiate a recursive search from the tree to the node, which enables the user's search (key, root) to be properly asked to the root node

void Btree::d estroy_tree ()
{
  destroy_tree (root);
}
The public version of the Destroy tree function is merely used to initialize the recursive Destroy_tree function which the n deletes all the nodes.

The Destroy_tree function, like a lookup, is used to start destroy_tree (root) to delete the nodes in the 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.