mafulechka
May 23, 2019, 12:49 p.m.

Tree data structure

A Linked List is a chain of nodes connected via "next" pointers. A tree is similar to a linked list, but each node can be linked to multiple nodes.

When we talk about a tree, we basically mean a binary tree, that is, a structure that has two children, left and right.


Binary tree representation

A binary tree node is represented by a structure containing a piece of data and two pointers to other structures of the same type.

  1. struct node
  2. {
  3. int data;
  4. struct node *left;
  5. struct node *right;
  6. };

A special pointer called ROOT points to the node that is the parent of all other nodes.

Also, nodes that have no children have their left and right pointers pointing to NULL .

A basic binary tree with three nodes can be created like this:

  1. /* Initialize nodes */
  2. struct node *root;
  3. struct node *one = NULL;
  4. struct node *two = NULL;
  5. struct node *three = NULL;
  6.  
  7. /* Allocate memory */
  8. one = malloc(sizeof(struct node));
  9. two = malloc(sizeof(struct node));
  10. three = malloc(sizeof(struct node));
  11.  
  12. /* Assign data values */
  13. one->data = 1;
  14. two->data = 2;
  15. three->data = 3;
  16.  
  17. /* Connect nodes */
  18. one->left = two;
  19. one->right = three;
  20. two->left = NULL;
  21. two->right = NULL;
  22. three->left = NULL;
  23. three->right = NULL;
  24.  
  25. /* Save address of first node in root */
  26. root = one;

In just a few steps, we have created a binary tree with three nodes.

Trees can be much deeper and more complex than this. The data stored in each node can be more complex, and have many more children than just two.

Applying trees

Trees and their variants are an extremely useful data structure with many practical uses.

  • Binary search trees (BST) are used to quickly check if an element is in a set.
  • Heap (Set) is a type of tree that is used to sort multiple elements.
  • A modified version of the tree called Tries is used in modern routers to store routing information.
  • The most popular databases use B-Trees (B-trees) and T-Trees (T-trees), which are variants of the tree structure we learned above to store their data.
  • Compilers use a syntax tree to check (validate) the syntax of every program you write.

Complete C program to implement Tree

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct node {
  5. int data;
  6. struct node* left;
  7. struct node* right;
  8. };
  9.  
  10. struct node* createNode(value){
  11. struct node* newNode = malloc(sizeof(struct node));
  12. newNode->data = value;
  13. newNode->left = NULL;
  14. newNode->right = NULL;
  15.  
  16. return newNode;
  17. }
  18.  
  19. struct node* insertLeft(struct node *root, int value) {
  20. root->left = createNode(value);
  21. return root->left;
  22. }
  23.  
  24.  
  25. struct node* insertRight(struct node *root, int value){
  26. root->right = createNode(value);
  27. return root->right;
  28. }
  29.  
  30. int main(){
  31. struct node *root = createNode(1);
  32. insertLeft(root, 2);
  33. insertRight(root, 3);
  34.  
  35. printf("The elements of tree are %d %d %d", root->data, root->left->data, root->right->data);
  36. }

Program output

1 2 3

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html