Data structure base temperature 4. Tree with two fork tree (top)

Source: Internet
Author: User

The linear table elements discussed above are a one-to-many relationship, and today we see a pair of relationships between the elements of the structure. Tree is widely used in computers, even in the daily use of computers, you can see the tree structure, as shown in the Windows Explorer and the Application menu is a tree-shaped structure. A tree structure is a typical nonlinear structure that can represent a hierarchical relationship in addition to representing adjacent relationships. This paper focuses on the basic structure and traversal algorithm of tree and two-fork tree.

A good big tree, Green Blessing 1.1 The basic concept of the tree

defination: A tree is a finite set of n (n≥0) nodes. When n=0, the tree is called the "Empty Tree". As shown, a point is called the root node, it has two subtrees trees, respectively, with B, c as the root, and C as the root of the subtree can be divided into two subtrees trees.

1.2 Basic terms of the tree

(1) Different nodes: the root node, the internal node, the leaf node, and the degree of the node

  (2) Node relationship: Parents and children, Daddy's back, where's daddy?

(3) Hierarchy of nodes: the level of the node is defined from the root, the root is the first layer, and the child of the root is the second layer. The maximum level of nodes in a tree is called the depth (Depth) or height of the tree.

Two or two what the hell is a tree? 2.1 from guessing the number game leads to the binary tree

Recall that a TV show will let the game participants guess the price of a product, if the participants in a limited time to guess the right, then he can obtain the product. A lot of people are just a little bit to raise the numbers to guess, but this guess would be inefficient. So a lot of smart people know that they need to use binary to find out what to guess. Given that a product is within the range of $100, you can guess the result in 7 times, as shown in: (because it is a positive integer within 100, so we first guess 50 (100 half), the defendant "big", then guess 25 (half of 50), the defendant's "small", Then guess 37 (the middle number of 25 and 50), small, so guess 43, big, 40, big, 38, small, 39, exactly right. )

As shown, for this case at a certain stage are two results, such as open and close, 0 and 1, true and false, up and down, right and wrong, positive and negative, etc., are suitable for modeling with a tree structure, and this tree is a very special tree structure, called two tree.

Features of the binary tree:

① Each node has a maximum of two subtrees trees, so there is no node of more than 2 in the binary tree.

② Saozi Right subtree is ordered, the order cannot be arbitrarily reversed.

③ even if a node in a tree has only one subtrees tree, it is Zuozi or right subtree to be distinguished.

2.2 Two binary tree sequential storage structure

The sequential storage structure of binary tree is to store the nodes in the binary tree with a one-dimensional array . The storage location of the node, that is, the subscript of the array to reflect the logical relationship between the nodes, such as the relationship between parents and children, the relationship between the brothers and so on.

But, consider an extreme situation, a tree with a depth of K, it has only k nodes, but it needs to allocate 2 K-square-1 storage unit space, which is obviously a waste of storage space, so, the sequential storage structure is generally only applicable to the complete binary tree .

2.3 Two-tree chain storage structure

Since sequential storage applicability is not strong, we need to consider the chain storage structure. The binary tree has a maximum of two children per node, so designing a data field and two pointer fields for it is a natural idea, and we call this a linked list called a two-cross list. Where data is the field, Lchild and Rchild are pointer fields, each holding a pointer to the left child and right child.

Three or two binary tree code implementation 3.1 two fork tree C # code implementation

(1) The definition of a binary tree node:

    /// <summary>    ///two node definition of a fork tree/// </summary>    /// <typeparam name= "T" >Data Specific type</typeparam>     Public classNode<t>    {         PublicT Data {Get;Set; }  PublicNode<t> Lchild {Get;Set; }  PublicNode<t> Rchild {Get;Set; }  PublicNode () {} PublicNode (T data) { This. data =data; }         PublicNode (T data, node<t> lchild, node<t>rchild) {             This. data =data;  This. lchild =Lchild;  This. rchild =Rchild; }    }
View Code

(2) binary tree to create the implementation:

        //METHOD01: Determine if the two-tree is an empty tree         Public BOOLIsEmpty () {return  This. root = =NULL; }        //Method02: Inserting data from the left child node under node p         Public voidInsertleft (node<t>p, T data) {Node<T> Tempnode =NewNode<t>(data); Tempnode.lchild=P.lchild; P.lchild=Tempnode; }        //METHOD03: Insert data from right child node under node p         Public voidInsertright (node<t>p, T data) {Node<T> Tempnode =NewNode<t>(data); Tempnode.rchild=P.rchild; P.rchild=Tempnode; }        //Method04: Delete left subtree under node p         PublicNode<t> Removeleft (node<t>p) {if(p = =NULL|| P.lchild = =NULL)            {                return NULL; } Node<T> Tempnode =P.lchild; P.lchild=NULL; returnTempnode; }        //Method05: Delete right subtree under node p         PublicNode<t> Removeright (node<t>p) {if(p = =NULL|| P.rchild = =NULL)            {                return NULL; } Node<T> Tempnode =P.rchild; P.rchild=NULL; returnTempnode; }
View Code

The above four methods provide the insertion of new nodes and the implementation of removal, we can insert for a node left child has right child node.

(3) Recursive traversal of binary tree:

First, we look at the three basic traversal of the binary tree through several graphs: the pre-order, the middle order, and the sequential traversal;

① Pre-sequence traversal: If the root node is not empty, the root node is accessed first, then the left subtree is traversed first, and the right subtree is traversed by the first order.

② sequence Traversal: If the root node is not empty, then the middle sequence traverses the left subtree, then accesses the root node, and finally the middle sequence traverses the right subtree;

③ post-order traversal: If the root node is not empty, the first step is to traverse the left sub-tree, followed by the right subtree, and finally access the root node;

        //Method01: Pre-sequence traversal         Public voidPreorder (node<t>node) {            if(Node! =NULL)            {                //root-left-rightConsole.Write (Node.data +" ");                Preorder (Node.lchild);            Preorder (Node.rchild); }        }        //Method02: Middle sequence traversal         Public voidMidorder (node<t>node) {            if(Node! =NULL)            {                //Left-to- root rightMidorder (Node.lchild); Console.Write (Node.data+" ");            Midorder (Node.rchild); }        }        //Method03: post-post traversal         Public voidPostorder (node<t>node) {            if(Node! =NULL)            {                //Left-to- right rootPostorder (Node.lchild);                Postorder (Node.rchild); Console.Write (Node.data+" "); }        } 
View Code

This implementation uses recursive method to implement traversal algorithm, mainly according to the requirements of the binary tree three traversal (pre-order, middle order and sequential traversal), sequentially output the elements of each node. The non-recursive traversal algorithm and the hierarchical traversal algorithm are described in the next article.

3.2 Testing the traversal method of binary tree

In the above code, we implement a recursive traversal algorithm for two-fork tree, where we construct a binary tree and traverse it through a simple test code. First, by looking at what kind of binary tree we're going to create?

(1) Test code:

        Static voidmybinarytreebasictest () {//constructs a binary tree with a root node of "A"mybinarytree<string> BTree =Newmybinarytree<string> ("A"); Node<string> RootNode =Btree.root; //Insert left child node "B" and Right child node "C" to root node "A"Btree.insertleft (RootNode,"B"); Btree.insertright (RootNode,"C"); //Insert left child node "D" and Right child node "E" to Node "B"node<string> NodeB =Rootnode.lchild; Btree.insertleft (NodeB,"D"); Btree.insertright (NodeB,"E"); //Insert right child node "F" to Node "C"node<string> NodeC =Rootnode.rchild; Btree.insertright (NodeC,"F"); //Pre-sequence traversalConsole.WriteLine ("---------Preorder---------");            Btree.preorder (Btree.root); //Middle Sequence TraversalConsole.WriteLine (); Console.WriteLine ("---------Midorder---------");            Btree.midorder (Btree.root); //Post-post traversalConsole.WriteLine (); Console.WriteLine ("---------postorder---------");        Btree.postorder (Btree.root); }

(2) Operation result:

Accessories download

This article implements the C # version of the binary Tree reference code download: Http://pan.baidu.com/s/1eQ1xmXs

Resources

(1) Geoscience, "Big liar data Structure"

(2) Chen Guang, "Data structure (C # language description)"

(3) Paragraph grace, "data structure (C # language Edition)"

(4) Yang Junming, "Data structure C # version notes-tree and two-fork tree"

(5) Frank Fan, "the high-rise level of the C # implementation of the two-tree operation"

Zhou Xurong

Source: http://edisonchou.cnblogs.com

The copyright of this article is owned by the author and the blog Park, welcome reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to give the original link.

Data structure base temperature 4. Tree with two fork tree (top)

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.