C program to draw a tree

In computer science, trees are among the most common thing that is used in data structures. They offer speedy insertion, deletion, and search functions together with an effective method of storing hierarchical data. Trees are used in many different contexts, such as database indexing, sorting algorithms, and hierarchical relationship representation. Pointers connecting nodes in a parent-child connection can be used to build trees in C programming. It makes it possible to model and modify the tree structure in code in an efficient manner. In this article, we'll examine a basic C implementation of a tree data structure. We will look at how to perform important operations such as insertion, deletion, and searching on trees, as well as describe the node structure. Gaining an understanding of trees is essential to learning C data structures and algorithms.

What is a Tree?

A tree is a type of nonlinear hierarchical data structure made up of nodes and edges. It has a root node at the top and leaf nodes at the bottom, with 0-no child nodes or more below each node. With a connection from each node back to its parent node, the nodes are linked in a parent-child relationship and contain data items. Trees are useful for representing a variety of data structures, including computer folder systems, database indexes, decision trees, parsers, and sorted lists that are easily searchable. The total number of edges on the longest path from the base to a leaf gives the tree its height. Data may be quickly added, removed, searched for, and sorted using trees, which are adaptable and flexible data structures.

Key Terminologies of Trees

There are several terminologies of Trees. Some main terminologies of the tree are as follows:

Nodes - Nodes are the building blocks of a tree data structure. Each node stores data and links to child nodes.

Root - The root node is the single node at the top of the tree hierarchy. It anchors the tree.

Parent-Child - Nodes are connected from top to bottom by parent-child relationships. Each node can link to child nodes below it.

Leaf - Leaves are nodes at the bottom level with no children. They indicate endpoints in the tree.

Subtree - A subtree is the portion of a tree made up of a node and all its descendants.

Height - Height measures the number of edges from root to lowest leaf. It indicates maximum depth.

Depth - Depth is the distance of a node from the root measured in edges. Root has depth 0.

Level - Level represents depth plus 1. The root is at level 1.

Degree - Degree is the number of subtrees/children of a node. Leaves have a degree of 0.

Binary Tree - Binary trees restrict nodes to at most 2 children. This structure is commonly used.

Binary Search Tree - BSTs order left and right subtrees such that left <= node < right to allow efficient searching.

Balanced Tree - Balanced trees even out the heights of subtrees. It enables efficient operations.

Full Tree - Full trees require each node to have 0 or 2 children (not 1).

Complete Tree - Complete trees fill all levels except the last and pack nodes left.

Forest - A forest contains multiple separate trees.

Traversal - Traversing a tree means visiting all nodes systematically, often recursively.

Key Properties of Trees

There are several properties of Trees. Some main properties of tree are as follows:

  • Hierarchical - A tree models hierarchical relationships between elements. Each element can have an arbitrary number of subordinate elements below it in a parent-child relationship.
  • Recursive - Trees are defined recursively where each node is itself a tree consisting of its descendants. Algorithms on trees are often defined recursively.
  • Rooted - Trees have a single root node at the top and grow downwards from it. The root node has no parents, and all other nodes ultimately link back to the root.
  • Labeled - Each node has a value associated with it, which is called its label or data element. Trees store data in their nodes.
  • Connected - All nodes are connected by edges from parent to child. Each node (except the root) has one incoming edge from its parent node.
  • Unordered - Nodes at each level are not ordered in any particular manner. The children of a node have no specific order.
  • Acyclic - Trees cannot have cycles. The edges have a specific direction from parent to child nodes, ruling out cycles.
  • Dynamic size - Trees can grow and shrink in size as nodes are added or removed. There is no fixed size for a tree.
  • Varying degree - Nodes can have any number of children or subtree sizes. Some nodes may have no children, while others have many.

Example:

Let's take an example to demonstrate how to create a tree in C.

Output:

Binary Tree (In-order traversal): 4 2 5 1 3

Explanation of important points:

  1. In this example, include h and stdlib.h header files for standard input/output and memory allocation functions.
  2. Define a TreeNode structure to represent each node in the binary tree. It contains an integer data value and pointers to left and right child nodes.
  3. Create a createNode() function to allocate memory for and initialize a new TreeNode. It sets the data value and child pointers to null.
  4. Define an inOrderTraversal() function to print the tree nodes in an in-order sequence (left subtree, root, right subtree). It traverses recursively if the root is not null.
  5. In main() function, first create the root node with data 1.
  6. Add left and right child nodes to the root with data 2 and 3.
  7. Add further left and right child nodes to node 2 with data 4 and 5.
  8. Print the tree by calling inOrderTraversal(), passing the root node. It will print the node values in sorted order.
  9. Free the memory allocated for each TreeNode by traversing from the leaves up to the root.
  10. Return 0 to indicate successful program execution.

Types of Trees:

There are several types of the Tree. Some important types of the tree are as follows:

  • Binary Tree- Each node has up to two child nodes referred to as left and right child. Binary trees are commonly used in binary search trees and heaps.
  • Binary Search Tree (BST)- A binary tree where the nodes are organized in order - the left subtree nodes are less than the parent, and the right subtree nodes are greater than the parent. Provides fast lookup, insertion and deletion.
  • AVL Tree- Self balancing binary search tree where the difference between the height of left and right subtrees of any node is not more than 1. Avoids skew and provides O(log n) lookup time.
  • Red-Black Tree- A self balancing BST where nodes have an extra color bit to ensure tree remains approximately balanced during insertions and deletions.
  • B-Tree- Tree where each node can have more than 2 children, up to some pre-defined order. Used in databases and file systems to enable efficient search and sequential access.
  • Heap- A specialized tree structure where parent nodes are ordered with respect to child nodes. Two common types are max-heap and min-heap, with the largest and smallest values at the root. Used to implement priority queues.
  • Trie- Tree where nodes store associative arrays indexed by characters. Enables efficient lookup and insertion of strings. Used in dictionaries, databases and spell checkers.
  • Suffix Tree- Specialized trie where suffixes of a given string are stored at the edges of the tree. Allows fast substring queries.

Tree Traversal:

1. Inorder Traversal

In this traversal, the left subtree is visited first, then the root node, and finally the right subtree. It is used to get nodes in sorted order in binary search trees.

Pseudocode:

2. Preorder Traversal

Here, the root node is visited first, then the left subtree, and finally the right subtree. It is useful to create a copy of the tree.

Pseudocode:

3. Postorder Traversal

In this traversal, the left subtree is visited first, then the right subtree, and finally the root node. It is used to delete trees or perform other clean up operations.

Pseudocode:

These three traversals allow you to systematically visit all nodes in a tree in different orders. They form the basis for many common tree operations.

Tree Applications:

There are several applications of Tree. Some important applications of tree are as follows:

Binary Search Trees (BSTs): It is used for efficient searching, insertion, and deletion of data, making them ideal for implementing dictionaries and symbol tables.

Expression Trees: It is used for representing mathematical expressions, allowing for efficient evaluation and simplification.

Heap Data Structure: A special type of binary tree used for implementing priority queues, such as binary heaps and Fibonacci heaps.

File Systems: Trees are used to represent directory structures in file systems. Each directory can contain files or subdirectories, forming a hierarchical structure.

Hierarchical Data Representation: Trees are used to represent hierarchical data, such as organization charts, family trees, and XML/JSON data structures.

Artificial Intelligence: Trees are used in decision tree algorithms for classification and regression tasks.