- Saved searches
- Use saved searches to filter your results more quickly
- License
- bradlet/cpptrees
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Дерево
- Способы обхода дерева
- Реализация дерева
- Добавление узлов в дерево
- Удаление поддерева
- Комментариев к записи: 19
- Build Binary Tree in C++ (Competitive Programming)
- Build Binary Tree in C++ (Competitive Programming)
- Introduction
- C++ Code – Inorder Traversal – Binary Tree
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A tree data structure library for c++.
License
bradlet/cpptrees
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
A tree data structure library for c++, made to be compatible with the GNU compiler.
Copyright © 2019 Bradley Thompson
This library will contain tree structure class templates. These should mimic the C Standard Template Library’s Containers.
The end product should provide most of the common functionality in an STL container. Therefore, the end goal will be efficiently implemented tree class templates that should be easy to utilize in any project.
Note: I followed this video when figuring out how to make a shared library. Don’t know if that counts as plagiarism when followed so I am including this just in case.
- Clone or download the contents of the repo.
- Type «make» to make the shared object (.so) file and tests, or just «make cpptrees» to make the .so file alone.
- Find where in your system libraries are stored (I used one of the four places in linux systems: usr/lib) and mv the .so file there.
Note: This likely requires administrator privileges.
ALTERNATIVELY JUST #include «tree.h» WITH tree.cpp AND tree.h IN THE CWD IF YOU WANT TO USE THIS WITHOUT THE HASTLE OF INSTALLING AS A LIBRARY (OR DON’T HAVE ADMIN PRIVELEGES)
If you know how to use the average STL container, you can use cpptrees. The BST class «BinaryTree» is essentially a set and has the same functionality.
- Objects of this class template require a type to be denoted, which is the type of data that will be stored in the node structures within the tree.
- find, begin, end, cbegin and cend all return BinaryIterator objects by reference. Use these if you want to be able to iterate through the tree using a for. each loop.
- empty reports whether a given tree object has data in it.
- size reports the current number of data entries in the tree.
- max_size reports the potential size of the tree, were it a full tree.
- insert adds an object of type T into the tree.
- swap exchanges the contents of one tree object with another.
- clear deletes all contents of a tree.
- count reports the number of times some piece of data occurs in the tree.
Development planned to be implemented after Summer 2019:
Licensed under the «MIT license», please reference LICENSE for more details.
About
A tree data structure library for c++.
Дерево
Дерево – структура данных, представляющая собой древовидную структуру в виде набора связанных узлов.
Бинарное дерево — это конечное множество элементов, которое либо пусто, либо содержит элемент ( корень ), связанный с двумя различными бинарными деревьями, называемыми левым и правым поддеревьями . Каждый элемент бинарного дерева называется узлом . Связи между узлами дерева называются его ветвями .
Способ представления бинарного дерева:
Корень дерева расположен на уровне с минимальным значением.
Узел D , который находится непосредственно под узлом B , называется потомком B . Если D находится на уровне i , то B – на уровне i-1 . Узел B называется предком D .
Максимальный уровень какого-либо элемента дерева называется его глубиной или высотой .
Если элемент не имеет потомков, он называется листом или терминальным узлом дерева.
Остальные элементы – внутренние узлы (узлы ветвления).
Число потомков внутреннего узла называется его степенью . Максимальная степень всех узлов есть степень дерева.
Число ветвей, которое нужно пройти от корня к узлу x , называется длиной пути к x . Корень имеет длину пути равную 0 ; узел на уровне i имеет длину пути равную i .
Бинарное дерево применяется в тех случаях, когда в каждой точке вычислительного процесса должно быть принято одно из двух возможных решений.
Имеется много задач, которые можно выполнять на дереве.
Распространенная задача — выполнение заданной операции p с каждым элементом дерева. Здесь p рассматривается как параметр более общей задачи посещения всех узлов или задачи обхода дерева.
Если рассматривать задачу как единый последовательный процесс, то отдельные узлы посещаются в определенном порядке и могут считаться расположенными линейно.
Способы обхода дерева
Пусть имеем дерево, где A — корень, B и C — левое и правое поддеревья.
Существует три способа обхода дерева:
- Обход дерева сверху вниз (в прямом порядке): A, B, C — префиксная форма.
- Обход дерева в симметричном порядке (слева направо): B, A, C — инфиксная форма.
- Обход дерева в обратном порядке (снизу вверх): B, C, A — постфиксная форма.
Реализация дерева
Узел дерева можно описать как структуру:
struct tnode <
int field; // поле данных
struct tnode *left; // левый потомок
struct tnode *right; // правый потомок
>;
При этом обход дерева в префиксной форме будет иметь вид
void treeprint(tnode *tree) <
if (tree!= NULL ) < //Пока не встретится пустой узел
cout field; //Отображаем корень дерева
treeprint(tree->left); //Рекурсивная функция для левого поддерева
treeprint(tree->right); //Рекурсивная функция для правого поддерева
>
>
Обход дерева в инфиксной форме будет иметь вид
void treeprint(tnode *tree) <
if (tree!= NULL ) < //Пока не встретится пустой узел
treeprint(tree->left); //Рекурсивная функция для левого поддерева
cout field; //Отображаем корень дерева
treeprint(tree->right); //Рекурсивная функция для правого поддерева
>
>
Обход дерева в постфиксной форме будет иметь вид
void treeprint(tnode *tree) <
if (tree!= NULL ) < //Пока не встретится пустой узел
treeprint(tree->left); //Рекурсивная функция для левого поддерева
treeprint(tree->right); //Рекурсивная функция для правого поддерева
cout field; //Отображаем корень дерева
>
>
Бинарное (двоичное) дерево поиска – это бинарное дерево, для которого выполняются следующие дополнительные условия (свойства дерева поиска):
- оба поддерева – левое и правое, являются двоичными деревьями поиска;
- у всех узлов левого поддерева произвольного узла X значения ключей данных меньше, чем значение ключа данных самого узла X ;
- у всех узлов правого поддерева произвольного узла X значения ключей данных не меньше, чем значение ключа данных узла X .
Данные в каждом узле должны обладать ключами, на которых определена операция сравнения меньше.
Как правило, информация, представляющая каждый узел, является записью, а не единственным полем данных.
Для составления бинарного дерева поиска рассмотрим функцию добавления узла в дерево.
Добавление узлов в дерево
struct tnode * addnode( int x, tnode *tree) <
if (tree == NULL ) < // Если дерева нет, то формируем корень
tree = new tnode; // память под узел
tree->field = x; // поле данных
tree->left = NULL ;
tree->right = NULL ; // ветви инициализируем пустотой
> else if (x < tree->field) // условие добавление левого потомка
tree->left = addnode(x,tree->left);
else // условие добавление правого потомка
tree->right = addnode(x,tree->right);
return (tree);
>
Удаление поддерева
void freemem(tnode *tree) <
if (tree!= NULL ) <
freemem(tree->left);
freemem(tree->right);
delete tree;
>
>
Пример Написать программу, подсчитывающую частоту встречаемости слов входного потока.
Поскольку список слов заранее не известен, мы не можем предварительно упорядочить его. Неразумно пользоваться линейным поиском каждого полученного слова, чтобы определять, встречалось оно ранее или нет, т.к. в этом случае программа работает слишком медленно.
Один из способов — постоянно поддерживать упорядоченность уже полученных слов, помещая каждое новое слово в такое место, чтобы не нарушалась имеющаяся упорядоченность. Воспользуемся бинарным деревом.
В дереве каждый узел содержит:
- указатель на текст слова;
- счетчик числа встречаемости;
- указатель на левого потомка;
- указатель на правого потомка.
Рассмотрим выполнение программы на примере фразы
now is the time for all good men to come to the aid of their party
При этом дерево будет иметь следующий вид
#include
#include
#include
#include
//#include
#define MAX WORD 100
struct tnode < // узел дерева
char * word; // указатель на строку (слово)
int count; // число вхождений
struct tnode* left; // левый потомок
struct tnode* right; // правый потомок
>;
// Функция добавления узла к дереву
struct tnode* addtree( struct tnode* p, char * w) int cond;
if (p == NULL ) p = ( struct tnode*)malloc( sizeof ( struct tnode));
p->word = _strdup(w);
p->count = 1;
p->left = p->right = NULL ;
>
else if ((cond = strcmp(w, p->word)) == 0)
p->count++;
else if (cond < 0)
p->left = addtree(p->left, w);
else
p->right = addtree(p->right, w);
return p;
>
// Функция удаления поддерева
void freemem(tnode* tree) if (tree != NULL ) freemem(tree->left);
freemem(tree->right);
free(tree->word);
free(tree);
>
>
// Функция вывода дерева
void treeprint( struct tnode* p) if (p != NULL ) treeprint(p->left);
printf( «%d %s\n» , p->count, p->word);
treeprint(p->right);
>
>
int main() struct tnode* root;
char word[MAX WORD ];
root = NULL ;
do scanf_s( «%s» , word, MAX WORD );
if (isalpha(word[0]))
root = addtree(root, word);
> while (word[0] != ‘0’ ); // условие выхода – ввод символа ‘0’
treeprint(root);
freemem(root);
getchar();
getchar();
return 0;
>
Результат выполнения
Комментариев к записи: 19
Build Binary Tree in C++ (Competitive Programming)
Let’s start our journey of learning a hierarchical data structure (BINARY TREE) in C++. We will start from very basic of creating a binary tree with the help of class and functions. In this tutorial, we will learn how to build binary tree in C++. Before that just grab some information about basics of Binary tree.
Build Binary Tree in C++ (Competitive Programming)
Introduction
A binary tree comprises of parent nodes, or leaves, each of which stores data and also links to up to two other child nodes (leaves) which are visualized spatially as below the first node with one placed to the left and with one placed to the right.
Some of the important points of a binary tree are:-
- A binary tree is made of nodes, where each node contains a left pointer (called the left subtree), a right pointer(called the right subtree), and a data element(data to be stored).
- The root pointer(node->root) points to the topmost node in the tree. A null pointer(NULL) represents a binary tree with no elements — >the empty tree.
- No order of data sorting is present in Binary tree.
Representation
It is generally represented as:
The code is provided in C++ along with the essential information of the functions and classes. So, we created a class Node comprising of :Data to be stored, Left subtree pointer, Right subtree pointer, Parameterised constructor(node) along with two functions:-
1. Build tree
2. Print (taking the root node as an argument)
The buildtree() inputs the value of data in variable d and root node is locally created with the data as d. The condition checks if the tree is empty (if empty return NULL) or not. The recursive call of function buildtree() is made on both left and right subtree of the binary tree and then root is returned.
The print() function accepting root node is used to print the entire binary tree. If the tree is empty, no tree is printed. Else, the data of the root node is printed first followed by the recursive call of print function on both left and right subtree. A binary tree is build up and printed in main function by calling both functions.
Certainly the easiest code with optimized space and time complexity. This code is represented as Inorder traversal.
C++ Code – Inorder Traversal – Binary Tree
#include using namespace std; class Node < public: int data; Node*left; Node*right; Node(int d)< data=d; left=NULL; right=NULL; >>; Node* buildtree()< int d; cin>>d; Node*root; if(d==-1) < return NULL; >root=new Node(d); root->left=buildtree(); root->right=buildtree(); return root; > void print(Node*root) < if(root==NULL)< return; >coutdataleft); print(root->right); > int main()