Binary tree two-fork linked list storage structure and C + + implementation

Source: Internet
Author: User

Tag: While it's font temp post cout enqueued output Enter

The key of storing binary tree is how to express the logical relationship between the nodes, that is, the relationship between parents and children. In a specific application, a child may be required to be directly accessible from either node.

One or two cross-linked list

Binary tree is generally used in binary chain list (binary linked list) storage, the basic idea is: each node of the binary tree corresponding to a linked List Node link table node in addition to storing the data information related to the two-fork tree node, but also to set the pointer to the left and right children. The node structure of the binary list is as follows:

Binary tree node structure
Lchild Data Rchild

of which, data is the domain, which holds the data information of the node;

Lchild is the left pointer field, which holds a pointer to the left child, and a null pointer when the left child does not exist;

Rchild is the right pointer field, which holds a pointer to the right child and a null pointer when the right child does not exist;

It is possible to describe the node of a binary linked list in the structure type of C + + language, because the node type of the binary list is uncertain, so the template mechanism of C + + is adopted. As follows:

1 // two nodes of a linked list 2 template<class t>3struct  binode4{5      T data;                            // data fields 6     Binode<t>*lchild, *rchild;    // left and right pointer fields 7 };        

Second, C + + implementation

The two-fork list storage structure of the two-fork tree is implemented in C + + classes. To prevent callers of the class from accessing the private variable root of the Bitree class, the corresponding private function is called in the constructor, destructor, and traversal functions.

The specific code is implemented as follows:

1. header file "Cirqueue.h"

This header file is the class implementation of the queue, and the sequence traversal is used to queue, so it defines a queue by itself.

1 #pragmaOnce2#include <iostream>3 Const intQueuesize = -;4template<classT>5 classQueue6 {7  Public:8         ....9 T data[queuesize];Ten     intfront, rear; One         .... A};

2. Header file "Bitree.h"

This header file is implemented as a class of two-linked lists.

#pragmaOnce#include<iostream>#include"cirqueue.h"//two nodes of a linked listtemplate<classT>structbinode{T data; //data fieldsBinode<t>*lchild, *rchild;//left and right pointer fields};//two cross-linked list class implementationtemplate<classT>classbitree{ Public: Bitree () {root= creat (root); }//constructor to build a binary tree~bitree () {Release (root);}//Destructors to free up storage space for each node    voidPreorder () {preorder (root);}//recursive pre-order traversal binary tree    voidInorder () {inorder (root);}//recursive middle sequence traversal binary tree    voidPostorder () {postorder (root);}//recursive sequential traversal of binary tree    voidLeverorder ();//sequence Traversal binary treePrivate: Binode<t>* Root;//head node pointing to the root nodebinode<t>* creat (binode<t>* BT);//Constructor Call    voidRelease (binode<t>* BT);//destructor Call    voidPreorder (binode<t>* BT);//Pre-sequence traversal function call    voidInorder (binode<t>* BT);//Middle sequence traversal function call    voidPostorder (binode<t>* BT);//Post- traversal function call};template<classT>inlinevoidBitree<t>:: Leverorder () {Queue<BiNode<T>*> Q;//Define a queueQ.front = Q.rear =-1;//Sequential Queue    if(Root = =NULL)return; q.data[++q.rear] =Root; The root pointer is enqueued while(Q.front! =q.rear) {Binode<t>* q = Q.data[++q.front];//out Teamcout << q->data; if(Q->lchild! =NULL) q.data[++q.rear] = q->lchild;//left child in the queue        if(Q->rchild! =NULL) q.data[++q.rear] = q->rchild;//Right Child team}}template<classT>inline Binode<t>* Bitree<t>::creat (binode<t>*BT)    {T ch; CIN>>ch; Enter data information for the node, assuming the characterif(ch = ='#')//Build an empty tree BT=NULL; Else{BT=NewBinode<t>; Generates a node with a data field of CH BT .->data =ch; BT->lchild = creat (bt->lchild); Recursive establishment of left sub-tree BT->rchild = creat (bt->rchild); Recursively build right subtree}returnBT;} Template<classT>inlinevoidBitree<t>::release (binode<t>*BT) {    if(BT! =NULL) {Release (BT-lchild); Release left dial hand tree release (BT-rchild); Free the right sub-treeDeleteBT; Releasing the root node}}template<classT>inlinevoidBitree<t>::P Reorder (binode<t>*BT) {    if(BT = =NULL)//End condition for recursive callreturn; cout<< bt->data; Access to the root node BT data domain preorder (BT-lchild); Pre-order recursive traversal of BT's left subtree preorder (BT-rchild); Pre-order recursive traversal of BT's right subtree}template<classT>inlinevoidBitree<t>::inorder (binode<t>*BT) {    if(BT = =NULL)return; Inorder (BT-lchild); cout<< bt->data; Inorder (BT-rchild);} Template<classT>inlinevoidBitree<t>::P Ostorder (binode<t>*BT) {    if(BT = =NULL)return; Postorder (BT-lchild); Postorder (BT-rchild); cout<< bt->data;}

description : 1, in addition to the sequence traversal, the other traversal is recursive algorithm.

2, why the sequence traversal uses the queue: in the sequence traversal, after a certain layer of the node access, and then according to their order of access to the left child and the right child sequence access to each node, so that a layer of the first access to the nodes of their children must first access, which conforms to the operation characteristics of the queue, therefore, When you perform a sequence traversal, you can set up a queue to hold the nodes that have been visited.

3, the constructor of the two-tree special processing: The two-tree each node of the null pointer to a virtual node, its value is a specific value, such as ' # ', to identify its empty.

4. The binary linked list is a dynamic memory allocation, and it is necessary to release all the nodes of the two-linked list in a destructor. When a node is released, the left and right sub-trees of the node are released, so the post-order traversal should be used.

3. Main function

1#include"bitree.h"2 using namespacestd;3 4 intMain ()5 {6bitree<Char>* bitree=Newbitree<Char> ();//create a two-pronged tree7Bitree->preorder ();//Pre-sequence traversal8cout <<Endl;9Bitree->inorder ();//Middle Sequence TraversalTencout <<Endl; OneBitree->postorder ();//Post-post traversal Acout <<Endl; -Bitree->leverorder ();//sequence Traversal -     DeleteBitree; the  -System"Pause"); -     return 0; -}

Third, examples

Build the following two-fork tree and output four traversal results.

Operation Result:

The results are correct.

Reference documents:

[1] Wang, Hu Ming, Wang Tao. Data structure (c + + version) [M]. Beijing: Tsinghua University Press.

Immediately New Year's Day, I wish you a happy New Year!! 2017-12-29

Binary tree two-fork linked list storage structure and C + + implementation

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.