Binary search tree (i) Text parsing and realization of C language

Source: Internet
Author: User

Overview

This chapter first introduces the relevant theoretical knowledge of two-fork tree, then gives the detailed implementation of C language. On the learning of binary tree, it is necessary to explain: it is not difficult, not only not difficult, but it is very simple. The first contact with the tree, I also think it seems difficult, and the resulting feeling is mainly due to the binary tree has a lot of unfamiliar concepts, properties and so on. And when I really realized the two-fork tree and looked back at its related concepts and properties, I thought it was so simple! Therefore, it is recommended to learn the binary tree when: The basic concept of the two-fork tree, the nature of a basic understanding, encountered difficult to understand the knowledge point, you can draw to help understand; After having a basic concept, it is important to do a two-fork search tree in person. At the end of the last round to summarize the theoretical knowledge of the binary tree, you will find--it is really simple! In code practice, I use the "binary search tree, rather than a simple two-fork tree" as an example of the illustration, simple two-tree is very simple, the actual usage is very small. Moreover mastered the two forks search tree, the binary tree also naturally grasps.

The two-fork search tree implemented in this article is in C language, and the following chapters give the implementation of C + + and Java versions respectively. You can practice learning according to your familiar language!

Be sure to understand, practice and master "binary search tree"! It is the cornerstone behind learning about AVL trees, stretching trees, red and black trees, and other related tree structures!

Directory
1. Introduction of the Tree
2. Introduction of two fork trees
3. C implementation of a two-fork lookup tree
4. C Test procedure for two-fork search tree

Reprint Please specify source: http://www.cnblogs.com/skywang12345/p/3576328.html

More information : Data structures and Algorithms series catalogs

(01). Two Fork Search tree (i) text parsing and C language implementation
(02). Two binary search tree (ii) Implementation of C + +
(03). Two Fork Search tree (c) Implementation of Java

Introduction to the tree

1. Definition of a tree

A tree is a data structure that consists of N (n>=1) of finite nodes that form a hierarchical set of relationships.

It's called a "tree" because it looks like an upside down tree, which means it's rooted up and leaves facing down. It has the following characteristics:
(01) Each node has 0 or more sub-nodes;
(02) A node without a parent node is called the root node;
(03) Each non-root node has and only one parent node;
(04) In addition to the root node, each child node can be divided into multiple disjoint subtrees.

2. Basic terminology of trees

If a node has a subtree, then the node is called the "parent" of subtree, and the root of the subtree is the "child" of the node. The nodes with the same parents are "brothers" to each other. Any node on all subtrees of a node is descended from that node. All nodes on the path from the root node to a node are ancestors of that node.

node degree : The number of subtrees owned by the node.
Leaf : A zero-degree junction.
Branch node : A node with a non-zero degree.
The degree of the tree : The maximum degree of the node in the tree.

hierarchy : The root node level is 1, the rest of the nodes are equal to the level of the parent node of the node plus 1.
height of the tree : The maximum level of nodes in the tree.
unordered tree : You can swap locations if the order of the sub-trees in the tree is unimportant.
ordered Tree : If the order of the sub-trees in the tree is important, the position cannot be exchanged.
Forest : consists of 0 or more disjoint trees. By adding a root to the forest, the forest becomes a tree; by deleting the root, the tree becomes the forest.

Introduction of Binary Tree

1. Definition of two-fork tree

A binary tree is a tree structure with a maximum of two subtrees per node. It has five basic forms: the two-fork tree can be an empty set, the root can have a left or right subtree, or the left and right subtrees are empty.

2. The nature of the two-fork tree

The binary tree has several properties: TODO (superscript and subscript)
Property 1: Two the number of nodes on the first layer of a fork tree is up to 2{i-1} (i≥1).
Property 2: A two-tree with a depth of K has a maximum of 2{k}-1 nodes (k≥1).
Property 3: The height of a two-fork tree containing n nodes is at least log2 (n+1).
Property 4: In any binary tree, if the number of terminal nodes is n0, the degree of 2 of the node is n2, then n0=n2+1.

2.1 Properties 1: Two forks tree the number of nodes on the first layer is 2{i-1} (i≥1)

Proof: The following "mathematical inductive method" to prove.
(01) When I=1, the number of nodes in layer I is 2{i-1}=2{0}=1. Because there is only one root node on the 1th floor, the proposition is set up.
(02) Assume that when i>1, the number of nodes in layer I is 2{i-1}. This is inferred from (01)!
According to this hypothesis, it is inferred that the "number of nodes in the i+1 layer is 2{i}".
Since there are at most two children per node of a binary tree, the number of nodes on the "i+1" is up to twice times the number of nodes in the layer I. That is, the maximum number of nodes on the (i+1) layer is =2x2{i-1}=2{i}.
It is assumed that the original proposition must be proved!

2.2 Nature 2: Two fork tree with a depth of k at most 2{k}-1 nodes (k≥1)

Proof: In a two-fork tree with the same depth, when each layer contains the maximum number of nodes, its tree has the most nodes. With "Property 1", the nodes of a two-tree with a depth of k are at most:
20+21+...+2k-1=2k-1
So the original proposition must be proven!

2.3 Property 3: The height of the two-fork tree containing n nodes is at least log2 (n+1)

Proof: According to the "Nature 2", it is known that the height of the two-fork tree has a maximum of 2{h}–1 nodes. Conversely, the height of a two-fork tree containing n nodes is at least log2 (n+1).

2.4 Properties 4: In any binary tree, if the number of terminal nodes is N0, the degree of 2 of the node is N2, then n0=n2+1

Proof: Because all nodes in the binary tree have no more than 2 degrees, the total number of nodes (recorded as n) = "0 degree node (n0)" + "1 degree node (n1)" + "2 degree node (n2)". Thus, get the equation one.
(Equation i) n=n0+n1+n2
On the other hand, 0-degree nodes have no children, 1-degree nodes have a child, 2-degree nodes have two children, so the total number of child nodes in the binary tree is: n1+2n2. In addition, only the root is not the child of any node. Therefore, the total number of nodes in the binary tree can be expressed as equation two.
(Equation II) n=n1+2n2+1
by (equation one) and (equation two) the computation is obtained: n0=n2+1. The original proposition to be proof!

3. Full two fork tree, complete binary tree and two fork find tree

3.1 Full two fork tree

definition : The height is h, and by the 2{h}–1 node of the two fork tree, is called full two fork tree.

3.2 Complete binary tree

definition : In a binary tree, only the bottom two levels of nodes can be less than 2, and the leaf nodes of the bottom layer are concentrated in several positions on the left. Such a two-fork tree is called a complete binary tree.
features : leaf nodes can only be present on the bottom and sub-lower, and the lowest leaf nodes are concentrated in the left part of the tree. Obviously, a tree full of two forks must be a completely binary tree, while a complete binary tree is not necessarily full of two forks.

3.3 Two fork Find tree

definition : Two-fork search tree, also known as binary tree. Set X as a node in the two-fork lookup tree, the x node contains the keyword key, and the key value of Node x is recorded as Key[x]. If Y is a node in the left subtree of x, then key[y] <= key[x], and if Y is a node of the right subtree of x, then key[y] >= key[x].

In the binary lookup tree:
(01) If the left subtree of any node is not empty, the value of all nodes on the left subtree is less than the value of its root node;
(02) The right subtree of any node is not empty, then the value of all nodes on the right subtree is greater than the value of its root node;
(03) The left and right sub-trees of any node are also two-fork search trees respectively.
(04) No nodes with key values equal (no duplicate nodes).

In practical application, the use of binary search tree is more. Below, use the C language to implement a two-fork lookup tree.

c Implementation of a two-fork lookup tree

1. Node definition

1.1 Node definition

typedef int TYPE;TYPEDEF struct bstreenode{    Type   key;                    Keywords (key value)    struct Bstreenode *left;    Left child    struct Bstreenode *right;    Right child    struct Bstreenode *parent;    Parent node}node, *bstree;

The nodes of the binary lookup tree contain the basic information:
Key-- a keyword that is used to sort the nodes of a two-fork lookup tree.
Left-it points to the child of the current node.
Right-it points to the child at the current node.
() Parent --it points to the parent nodes of the current node.

1.2 Creating nodes

Code to create a node

Static node* Create_bstree_node (Type Key, node *parent, node *left, node* right) {    node* p;    if (p = (node *) malloc (sizeof (node)) = = null)        return null;    P->key = key;    P->left = left;    P->right = right;    P->parent = parent;    return p;}

2 traversal

This explains the pre-sequence traversal , the middle sequence traversal, the post-order traversal 3 kinds of ways.

2.1 Pre-sequence traversal

If the binary tree is not empty, do the following:
(01) Access to the root node;
(02) The first sequence traverses the left subtree;
(03) The first sequence traverses the right subtree.

Pre-order Traversal code

void Preorder_bstree (Bstree tree) {    if (tree! = NULL)    {        printf ("%d", tree->key);        Preorder_bstree (tree->left);        Preorder_bstree (tree->right);    }}

2.2 Middle Sequence traversal

If the binary tree is not empty, do the following:
(01) The middle sequence traverses the left subtree;
(02) Access to the root node;
(03) The middle sequence traverses the right sub-tree.

Middle-order Traversal code

void Inorder_bstree (Bstree tree) {    if (tree! = NULL)    {        inorder_bstree (tree->left);        printf ("%d", tree->key);        Inorder_bstree (tree->right);    }}

2.3 Post-post traversal

If the binary tree is not empty, do the following:
(01) to traverse the left subtree;
(02) to traverse the right sub-tree;
(03) Access to the root node.

Post-Traversal code

void Postorder_bstree (Bstree tree) {    if (tree! = NULL)    {        postorder_bstree (tree->left);        Postorder_bstree (tree->right);        printf ("%d", Tree->key);}    }

These traversal methods are described in the following example.

For the above two-fork tree,
(01) Pre-sequence Traversal results: 3 1 2 5 4 6
(02) Middle sequence Traversal result: 1 2 3 4 5 6
(03) post-Post traversal results: 2 1 4 6 5 3

3. Find

Recursive version of the code

node* Bstree_search (Bstree x, Type key) {    if (X==null | | x->key==key)        return x;    if (Key < X->key)        return Bstree_search (X->left, key);    else        return Bstree_search (X->right, key);}

Non-recursive version of the code

node* Iterative_bstree_search (Bstree x, Type key) {while    ((x!=null) && (X->key!=key))    {        if ( Key < X->key)            x = x->left;        else            x = x->right;    }    return x;}

4. Maximum value and minimum value

Code to find the maximum value

node* bstree_maximum (Bstree tree) {    if (tree = = null)        return null;    while (tree->right! = NULL)        tree = tree->right;    return tree;}

Code to find the minimum value

node* bstree_minimum (Bstree tree) {    if (tree = = null)        return null;    while (tree->left! = NULL)        tree = tree->left;    return tree;}


5. Precursors and Successors

The predecessor of the node : is the largest node in the left subtree of the node.
successor of the node : is the smallest node in the right subtree of the node.

Find the code for the precursor node

node* bstree_predecessor (Node *x) {    //If X has a left child, then "X's Precursor node" is the largest node of the subtree with its left child as its root.    if (x->left! = NULL)        return Bstree_maximum (x->left);    If X has no left child. X has the following two possibilities:    //(a) x is "a right child", then "X's predecessor Node" is "its parent node".    //(*) x is "a left child", then looks for "the lowest parent node of X, and the parent node to have right child", the "lowest parent node" found is "X's precursor node".    node* y = x->parent;    while ((Y!=null) && (x==y->left))    {        x = y;        y = y->parent;    }    return y;}

Find the code for the successor node

node* bstree_successor (Node *x) {    //if x exists right child, then "X's successor" is "the smallest node of a subtree with its right child root".    if (x->right! = NULL)        return Bstree_minimum (x->right);    If X does not have right child. X has the following two possibilities:    //(a) x is "a left child", then "X's successor" is "its parent node".    //() x is "a right child", then look for "the lowest parent node of X, and the parent node to have left child", the "lowest parent node" found is "the successor of X".    node* y = x->parent;    while ((Y!=null) && (x==y->right))    {        x = y;        y = y->parent;    }    return y;}

6. Insert

Code to insert a node

Static node* Bstree_insert (Bstree Tree, node *z) {    node *y = NULL;    Node *x = tree;    Finds the insertion position of Z    while (x! = NULL)    {        y = x;        if (Z->key < X->key)            x = x->left;        else            x = x->right;    }    Z->parent = y;    if (y==null)        tree = z;    else if (Z->key < Y->key)        y->left = Z;    else        y->right = Z;    return tree;} node* insert_bstree (bstree tree, Type key) {    Node *z;    New node    //If the new node fails, it is returned.    if (Z=create_bstree_node (key, NULL, NULL, NULL)) = = NULL)        return tree;    Return Bstree_insert (tree, z);}

Bstree_insert (tree, z) is an intrinsic function that inserts a node (z) into a two-bit tree and returns the root node after the node is inserted.
Insert_bstree (tree, key) is an external interface, which functions as a new node in the tree, key is the value of the node, and returns the root node after the insertion of the node.

Note: The two-fork search tree implemented in this article is a node that allows inserting the same key values! If the user does not want to insert a node with the same key value, modify the Bstree_insert () to the following code.

Static node* Bstree_insert (Bstree Tree, node *z) {    node *y = NULL;    Node *x = tree;    Finds the insertion position of Z    while (x! = NULL)    {        y = x;        if (Z->key < X->key)            x = x->left;        else  if (Z->key > X->key)            x = x->right;        else        {            free (z);//release previously assigned system.            return tree;        }    }    Z->parent = y;    if (y==null)        tree = z;    else if (Z->key < Y->key)        y->left = Z;    else        y->right = Z;    return tree;}

7. Delete

Code to delete a node

Static node* Bstree_delete (Bstree Tree, node *z) {    node *x=null;    Node *y=null;    if ((Z->left = = NULL) | | (Z->right = = NULL))        y = Z;    else        y = Bstree_successor (z);    if (y->left! = NULL)        x = y->left;    else        x = y->right;    if (x = NULL)        x->parent = y->parent;    if (y->parent = = NULL)        tree = x;    else if (y = = y->parent->left)        y->parent->left = x;    else        y->parent->right = x;    if (Y! = z)         z->key = y->key;    if (y!=null) free        (y);    return tree;} node* delete_bstree (bstree tree, Type key) {    Node *z, *node;     if (z = Bstree_search (tree, key)) = NULL)        tree = Bstree_delete (tree, z);    return tree;}

Bstree_delete (tree, z) is an intrinsic function that removes the node (z) from the binary tree and returns the root node after the node is deleted.
Delete_bstree (tree, key) is an external interface, which is to look for a node with a key value in the tree, delete the node if found, and return the root node after the node is deleted.


8. Printing

Code to print a binary tree

void Print_bstree (Bstree tree, Type key, int direction) {    if (tree! = NULL)    {        if (direction==0)    // The tree is the root node            printf ("%2d is root\n", tree->key);        else                //tree is the branch node            printf ("%2d is%2d ' s%6s child\n", Tree->key, Key, Direction==1? " Right ":" Left ");        Print_bstree (Tree->left, Tree->key,-1);        Print_bstree (Tree->right,tree->key,  1);}    }

The role of print_bstree (tree, key, direction) is to print the entire binary tree. Where Tree is a two-fork tree node and key is a key value for a two-fork tree, and direction represents the type of the node:

The direction is 0, indicating that the node is the root node;
Direction is-1, which indicates that the node is the left child of its parent junction;
Direction is 1, which indicates that the node is the right child of its parent node.

9. Destroying the binary tree

Destroy the binary tree code

void Destroy_bstree (Bstree tree) {    if (tree==null)        return;    if (tree->left! = NULL)        destroy_bstree (tree->left);    if (tree->right! = NULL)        destroy_bstree (tree->right);    Free (tree);}

Complete implementation Code

Binary Lookup Tree header file (bstree.h)

View Code

Implementation file for binary lookup tree (bstree.c)

View Code

Test procedure for Binary search tree (BTREE_TEST.C)

View Code

C test program for binary search tree

The btree_test.c above is a two-fork search tree test program that runs the following results:

= = Add: 1 5 4 3 2 6 = = pre-sequence traversal: 1 5 4 3 2 6 = = Sequence Traversal: 1 2 3 4 5 6 = = Post Traversal: 2 3 4 6 5 1 = min: 1== max: 6== tree Details:  1 is Root 5 is 1 's right child 4 is 5 's left child 3 is 4 's left child  2 was  3 ' s left child   6 I S  5 ' s  

The following is an analysis of the process of the test program!

(01) Create a "binary search tree" root.

(02) Insert the 1,5,4,3,2,6 in the binary lookup tree in turn. As shown in the following:

(03) Information about the printing tree
After inserting 1,5,4,3,2,6, the resulting two-fork lookup tree is as follows:

Pre-sequence Traversal results: 1 5 4 3 2 6
Middle Sequence Traversal results: 1 2 3 4 5 6
Post-Post Traversal results: 2 3 4 6 5 1
The minimum value is 1, and the maximum value is 6.

(04) Delete Node 3. As shown in the following:

(05) Re-traverse the two-fork lookup tree.
Middle Sequence Traversal results: 1 2 4 5 6

Binary search tree (i) Text parsing and realization of C language

Related Article

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.