[data structure] – traversal algorithm of binary tree

Time:2021-3-2

Title Requirements

Write a program to establish the binary list storage structure of the binary tree by using the preorder recursive traversal calendar (or input preorder and middle order recursive traversal node access sequence), calculate and output the total number of nodes and tree height of the binary tree, and then output its preorder, middle order, post order and hierarchical traversal node access order. The implementation of hierarchical traversal needs to use circular queue. The character type is recommended for the node data type of binary tree.

Data structure design

Using C + + template class to create queue. In each queue object, the element pointer is used to create an array of length N, n represents the capacity of the queue, front represents the head pointer, real represents the tail pointer, and C represents the number of current elements in the queue.
The binary tree is established by structure, where data represents data field, lchild represents left pointer, rchild represents right pointer, bit represents pointer type variable of binary tree structure, and bitnode represents binary tree structure type variable.

Brief description of algorithm design

  1. First traversal to establish binary tree: recursively call functions, read characters continuously, establish left subtree and right subtree in turn, when read ‘#’ character, return null pointer, and finally return root node pointer.
  2. Firstly, the preorder and the middle order traverse the node access sequence to build a binary tree
    a. First, the root node is obtained from the preorder sequence;
    b. From the position of the root node in the middle order sequence, we know that the node visited before it is its left subtree node, and the node visited after it is its right subtree node;
    c. Recursive application of a, B two.

Program code

#include <conio.h>
#include <iostream>
using namespace std;
typedef char ElemTp;
#define MAX 20
template <typename T>
Class queue // template class: queue
{
public:
    Queue(); // default constructor
    Queue (int n); // the constructor calls the function createqueue (int n) to create a queue of length n
    ~Queue(); // fictitious function
    Int createqueue (int n); // create a queue of length n
    Int empty(); // judge whether the queue is empty
    Int full(); // judge whether the queue is full
    Int enqueue (t e); // element E joins the queue
    Int dlqueue (T & E); // the element is out of the queue and saved in E
private:
    T * elem; // create an array of length n
    Int n; // queue capacity
    Int front; // team head pointer
    Int real; // end of line pointer
    Int c; // the current number of elements in the queue
};
typedef struct node
{
    Elemtp data; // data field
    Struct node * lchild, // left pointer
        *Rchild; // right pointer
}*BiT,BiTNode;
 
Void visit (bit E) // access function      
{
    If (E - > data! = null) // output the data field of the binary tree
        cout << e->data << "  ";
}
Void preorder (bit BT) // traverse the binary tree first
{
    if (bt)
    {
        Visit (BT); // visit the root node
        Preorder (BT - > lchild); // recursively call to traverse the left subtree
        Preorder (BT - > rchild); // recursively call to traverse the right subtree
    }
}
Void midoder (bit BT) // traversing binary tree in middle order
{
    if (bt)
    {
        Midoder (BT - > lchild); // recursively call to traverse the left subtree
        Visit (BT); // visit the root node
        Midoder (BT - > rchild); // recursively call to traverse the right subtree
    }
}
Void lasorder (bit BT) // traversing binary tree in post order
{
    if (bt)
    {
        Lasorder (BT - > lchild); // recursively call to traverse the left subtree
        Lasorder (BT - > rchild); // recursively call to traverse the right subtree
        Visit (BT); // visit the root node
    }
}
Void layertravel (bit BT) // traversing binary tree hierarchically
{
    if (bt == NULL)
        return;
    Queue < bit > Q (max); // establish a queue
    q. Enqueue (BT); // the root node is queued
    while (!q.empty())
    {
        q. Dlqueue (BT); // root node out of the queue
        Visit (BT); // visit the root node
        if (bt->lchild)
            q. Enqueue (BT - > lchild); // the left subtree is not empty, visit the left subtree
        if (bt->rchild)
            q. Enqueue (BT > rchild); // the right subtree is not empty, access the right subtree
    }
}
Bit crtprebt() // binary tree algorithm based on recursive traversal
{
    BiT bt;
    char ch;
    ch = getchar();
    If (CH = = '#' // returns null pointer after reading '#'
        return NULL;
    BT = new bitnode(); // create a new binary tree node
    bt->data = ch;
    Bt - > lchild = crtprebt(); // recursively establish left subtree
    Bt - > rchild = crtprebt(); // recursively establish the right subtree
    return bt;
}
Bit crtpremidbt (char * PR, int & I, char * MI, int u, int V) // recursively traverse the node access sequence to build a binary tree algorithm
{
    BiT bt;
    int k;
    if (u > v)
        return NULL;
    bt = new BiTNode();                     
    Bt - > data = PR [i + +]; // PR [i] is the root node of the subtree
    For (k = u; K < = V; K + +) // MI [u... V] is the middle order sequence of subtree
    {
        If (MI [k] = = bt - > data) // find the position of the root node in the middle sequence
            break;
    }
    Bt - > lchild = crtpremidbt (PR, I, MI, u, K - 1); // recursively establish the left subtree
    Bt - > rchild = crtpremidbt (PR, I, MI, K + 1, V); // recursively establish the right subtree
    return bt;
}
Int height (bit BT) // calculate the height of the binary tree
{
    int hl, hr;
    if (!bt)
        return 0;
    HL = height (BT - > lchild); // recursively calculate the height of the left subtree
    HR = height (BT - > rchild); // recursively calculate the height of the right subtree
    Return (HL > HR)? (HL + 1): (HR + 1); // returns the height of the entire binary tree (the value with the higher height of the left and right subtrees plus one)
}
Int nodenum (bit BT) // calculates the total number of binary trees
{
    int nl, nr;
    if (!bt)
        return 0;
    NL = nodenum (BT - > lchild); // recursively calculate the number of nodes of the left subtree  
    NR = nodenum (BT - > rchild); // recursively calculate the number of nodes of the right subtree
    Return NL + NR + 1; // returns the number of nodes of the entire binary tree (the sum of nodes of the left and right subtrees plus one)
}
Void choose (bit & BT) // select the way to build binary tree
{
    char num, pre[MAX], mid[MAX];
    int i = 0, u = 0, v;
    Cout < "please select the way to build binary tree": < endl;
    Cout < "1. Build a binary tree by traversing the binary tree first" < endl;
    Cout < "2. Traversing preorder and middle order to build binary tree" < endl;
    num = _getch();
    switch (num)
    {
    Case '1': // traversing the binary tree first
    {
        Cout < "you chose the first way." < endl;
        Cout < "please input the character sequence traversed in the previous order: < endl;
        bt = crtPreBT();
    }   break;
    Case '2': // traversing preorder and middle order to build binary tree
    {
        Cout < "you chose the second way." < endl;
        Cout < "please input the character sequence traversed in the previous order: < endl;
        cin.getline(pre, MAX);
        Cout < "please input the character sequence traversed by middle order: < endl;
        cin.getline(mid, MAX);
        v = strlen(mid) - 1;
        bt = crtPreMidBT(pre, i, mid, u, v);
    }   break;
    }
}
template<typename T>
Queue<T>::Queue()                           
{
    front = rear = -1;
    c = 0;
}
template<typename T>
Queue<T>::Queue(int n)                          
{
    createQueue(n);
}
template<typename T>
Queue<T>::~Queue()
{
    c = 0;
    front = rear = -1;
    delete[]elem;
}
template<typename T>
int Queue<T>::createQueue(int n)
{
    if (n <= 0)
        return 0;
    this->n = n;
    c = 0;
    front = rear = -1;
    elem = new T[n];
    if (!elem)
        return 0;
    return 1;
}
template<typename T>
int Queue<T>::empty()
{
    return c == 0;
}
template<typename T>
int Queue<T>::full()
{
    return c == n;
}
template<typename T>
int Queue<T>::enQueue(T e)
{
    if (c == n)
        Return 0; // the team is full and failed to join
    rear = (rear + 1) % n;
    elem[rear] = e;
    c++;
    Return 1; // team successfully returns 1
}
template<typename T>
int Queue<T>::dlQueue(T & e)
{
    if (c == 0)
        Return 0; // if the team is empty, it fails to leave
    front = (front + 1) % n;
    e = elem[front];
    c--;
    Return 1; // 1 returned after successfully leaving the team
}
int main()
{
    int h, num;
    BiT bt;
    choose(bt);
    h = height(bt);
    Cout < "the height of binary tree is: < h < endl;
    num = nodeNum(bt);
    Cout < "the sum points of binary tree are: < num < < endl;
    Cout < "access order of traversal nodes in advance": < endl;
    preorder(bt);
    cout << endl;
    Cout < < middle order traversal node access order: < endl;
    midorder(bt);
    cout << endl;
    Cout < "post order traversal node access order": < endl;
    lasorder(bt);
    cout << endl;
    Cout < "hierarchy traversal node access order: < endl;
    layertravel(bt);
    cout << endl;
    return 0;
}

Examples

(1)Program input
Sequence: ABC # de # g # f###
Program output
The height of the binary tree is: 5
The total number of binary trees is: 7
Preorder traversal: a b c d e g f
Middle order traversal: C B e g d f a
Postorder traversal: C G E F D B a
Hierarchy traversal: a B C D E F G
[data structure] - traversal algorithm of binary tree
(2)Program input
Sequence: ABCDEFG
Middle sequence: cbedafg
Program output
The height of the binary tree is: 4
The total number of binary trees is: 7
Preorder traversal: a B C D E F G
Middle order traversal: C B e d a F G
Postorder traversal: c e d b g f a
Level traversal: a b f c d g e
[data structure] - traversal algorithm of binary tree
(3)Program input
The sequence: abdf ##################################
Program output
The height of the binary tree is: 5
The total number of binary trees is 8
Preorder traversal: a B D f c e g h
Middle order traversal: F D B a c e g h
Postorder traversal: F D b h g e c a
Hierarchy traversal: a B C D E F G H
[data structure] - traversal algorithm of binary tree
(4)Program input
Preorder sequence:#
Program output
The height of the binary tree is: 0
The sum point of binary tree is: 0
[data structure] - traversal algorithm of binary tree