A Binary Tree is a type of tree data structure where each node has at most two children, referred to as the left and right child. It is widely used in various applications, such as searching, sorting, and hierarchical data storage. Each node in a binary tree consists of three parts: data, left child, and right child.
A binary tree can be represented by the following 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;
}
There are several variations of binary trees, including:
There are four main traversal methods in binary trees:
Here's a code example that demonstrates binary tree creation and various traversal methods:
// 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);
}
// Level Order Traversal
void levelOrderTraversal(struct Node* root) {
if (root == NULL) return;
struct Queue* q = createQueue();
enqueue(q, root);
while (!isEmpty(q)) {
struct Node* node = dequeue(q);
printf("%d ", node->data);
if (node->left) enqueue(q, node->left);
if (node->right) enqueue(q, node->right);
}
}
Binary trees are widely used in various real-life applications:
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!