Скачиваний:
16
Добавлен:
18.03.2018
Размер:
2.03 Кб
Скачать
//Построить полное бинарное дерево уровня N, в котором значения каждого узла равны номеру уровня.
//Связная структура хранения

#include <iostream>
#include <cstdlib>

using namespace std;


class tree
{
   struct node
   {
      int info;
      node *left, *right;
   } *pn;

typedef struct node * DataType;
#include "queue.cpp"

    node * new_node (int x)
    {
        node *ptr;
        ptr = new node;
        ptr->info = x;
        ptr->left = ptr->right = NULL;
        return ptr;
    }

    node* add_node(int x, node* pn)
    {
        node *ptr = pn;
        if (pn == NULL)
          return new_node (x);
        pn->left = add_node (x, pn->left);
        pn->right = add_node (x, pn->right);
        return ptr;
    }

    void print_s (node* pn)
    {
        if (pn->left)
          print_s (pn->left);
        cout << pn->info << " ";
        if (pn->right)
          print_s (pn->right);
    }
    
    void del_tree(node*pn)
    {
        if (pn->left)
          del_tree(pn->left);
        if (pn->right)
          del_tree(pn->right);
        delete pn;
    }

public:
         
    tree(): pn(NULL) {}
    
    ~tree()
    {
        del_tree(pn);
    }
    
    void add (int x)
    {
         pn = add_node (x, pn);
    }
    
    void print_sim (void)
    {
         print_s (pn);
    }
    
    void print_pop (void)
    {
        Queue q;
        q.EnQueue(pn);
        while (!q.Empty())
        {
              pn = q.DeQueue();
              cout << pn->info << " ";
              if (pn->left) q.EnQueue(pn->left);
              if (pn->right) q.EnQueue(pn->right);
        }
    }
};
 
main()
{
    int  i, N;
    tree t;

    do
    {
        cout << "N = ";
        cin >> N;
    }while(N<=0);
    cout << endl;
    for(i=0; i<=N; i++)
        t.add(i);
    cout << endl;
    t.print_sim ();
    cout << endl;
    t.print_pop ();
    cout << endl;
    system("pause");
    return 0;
}
Соседние файлы в папке tree_N_ptr