A Tree is a hierarchical data structure that consists of nodes connected by edges. It is commonly used to represent relationships, such as organizational hierarchies, file systems, or decision processes. A tree is a non-linear structure, unlike arrays or linked lists, and follows a parent-child relationship.
Some of the most commonly used tree types in DSA include:
A tree consists of the following components:
Tree traversal refers to visiting all nodes in a specific order. The common types of tree traversal are:
Below is a simple example of a binary tree structure:
// Binary Tree Node Structure
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Create a new node
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->left = newNode->right = NULL;
return newNode;
}
// Preorder Traversal
void preorderTraversal(struct Node* root) {
if (root == NULL) return;
printf("%d ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// Inorder Traversal
void inorderTraversal(struct Node* root) {
if (root == NULL) return;
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
// Postorder Traversal
void postorderTraversal(struct Node* root) {
if (root == NULL) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->data);
}
int main() {
struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
printf("Preorder Traversal: ");
preorderTraversal(root);
printf("\n");
printf("Inorder Traversal: ");
inorderTraversal(root);
printf("\n");
printf("Postorder Traversal: ");
postorderTraversal(root);
printf("\n");
return 0;
}
Trees are widely used in various computer science applications:
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!