#include <stdio.h>
#include <stdlib.h>
// Define the structure for a node in the tree
struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
};
// Function to create a new node
struct TreeNode* createNode(int data) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Function to insert a node in the tree (basic BST insert)
struct TreeNode* insertNode(struct TreeNode* root, int data) {
if (root == NULL) {
return createNode(data); // If the tree is empty, create the first node
}
if (data < root->data) {
root->left = insertNode(root->left, data); // Insert in the left subtree
} else {
root->right = insertNode(root->right, data); // Insert in the right subtree
}
return root;
}
// Function for inorder traversal (Left, Root, Right)
void inorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left); // Traverse the left subtree
printf("%d ", root->data); // Print the data of the current node
inorderTraversal(root->right); // Traverse the right subtree
}
// Main function
int main() {
struct TreeNode* root = NULL;
// Insert nodes into the tree
root = insertNode(root, 50);
insertNode(root, 30);
insertNode(root, 20);
insertNode(root, 40);
insertNode(root, 70);
insertNode(root, 60);
insertNode(root, 80);
// Print inorder traversal of the tree
printf("Inorder traversal of the tree: \n");
inorderTraversal(root); // Output: 20 30 40 50 60 70 80
return 0;
}
Comments
Post a Comment