[ Новые сообщения · Участники · Правила форума · Поиск · RSS ]
  • Страница 1 из 1
  • 1
дерево и левосторонний выход
paulДата: Чт, 30 Апр 2015, 18:22 | Сообщение # 1
Выучил типы
Группа: Кодеры
Сообщений: 3
Репутация: 1
Статус: Offline

Код
// treehouse.cpp: определяет точку входа для консольного приложения.
//дерево случайных уникальных чисел (для примера от 1 до 50) и его левосторонний обход

#include "stdafx.h"
#include <iostream>
#include<time.h>
#include<windows.h>
#include <string>

using namespace std;

struct TreeH
{
    int num;
    TreeH* left;
    TreeH* right;
};

TreeH* init(int N)
{
    TreeH* tree = new TreeH;
    tree->num = N;
    tree->left = NULL;
    tree->right = NULL;
    return tree;
}

void createTREE(TreeH* current, TreeH* next)
{
    if (next->num < current->num)
    {
       if (current->left == NULL)
          current->left = next;
       else
          createTREE(current->left, next);
    }
        
    if (next->num > current->num)
    {
       if (current->right == NULL)
          current->right = next;
       else
          createTREE(current->right, next);
    }
}

int OutputTREE(TreeH* root)
{
    cout << root->num << " ";
    while (root->left != NULL && OutputTREE(root->left)!=NULL)
    {
       root = root->left;
       OutputTREE(root);
    }
    if (root->right != NULL && OutputTREE(root->right) != NULL)
    {
       root = root->right;
       OutputTREE(root);
    }
    if (root->left == NULL && root->right == NULL)
    {
       cout << "- Это листок. Следующая ветка:"<<endl;
       return NULL;
    }
    else
       return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
    setlocale(LC_ALL, "Russian");
    srand(time(NULL));
    //создаю массив случайных чисел без повторов.
    int num = 0;
    bool isin = false;
    int arr[50] = { 0 };
    for (int i = 0; ; i++)
    {
       num = rand() % 51 + 1;
       int j = 0;
       while (arr [j]!= 0)
       {
          if (arr [j]== num)
          {
             arr [j]= num;
             isin = true;
          }
          j++;
       }
       if (arr[j]==0 && isin==false)
          arr [j]= num;
       isin = false;
       if (j == 49 && arr [j]!= 0)
          break;
    }
    //массив создан. теперь выведем его
    cout << "Числа, которые принимают участие в создании дерева:" << endl;
    for (int i = 0; i < 50; i++)
       cout << arr [i]<< "  ";
    cout << endl;
    //теперь создадим дерево с элементами этого массива
    TreeH* tree = new TreeH;
    tree = init(arr[0]);
    for (int i = 1; i < 50; i++)
    {
       createTREE(tree, init(arr[i]));
    }
    //дерево, наверное, создано, теперь выводим его
    cout << "Дерево, которое у нас получилось:" << endl;
    OutputTREE(tree);

    system("pause");
    return 0;
}
 
  • Страница 1 из 1
  • 1
Поиск: