0% found this document useful (0 votes)
23 views

tree c dsa program

Uploaded by

Sid1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

tree c dsa program

Uploaded by

Sid1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <stdlib.h>

// Define the structure for a tree node


typedef struct Node {
char data;
struct Node* left;
struct Node* right;
} Node;

// Function to create a new node


Node* createNode(char data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory error\n");
return NULL;
}
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

// Function to perform inorder traversal


void inorderTraversal(Node* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%c ", root->data);
inorderTraversal(root->right);
}

// Function to perform preorder traversal


void preorderTraversal(Node* root) {
if (root == NULL) {
return;
}
printf("%c ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}

// Function to perform postorder traversal


void postorderTraversal(Node* root) {
if (root == NULL) {
return;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%c ", root->data);
}

// Function to visualize the tree


void visualizeTree(Node* root, int level) {
if (root == NULL) {
return;
}
visualizeTree(root->right, level + 1);
for (int i = 0; i < level; i++) {
printf(" ");
}
printf("%c\n", root->data);
visualizeTree(root->left, level + 1);
}

int main() {
Node* root = createNode('A');
root->left = createNode('B');
root->right = createNode('C');
root->left->left = createNode('D');
root->left->right = createNode('E');

printf("Inorder Traversal: ");


inorderTraversal(root);
printf("\n");

printf("Preorder Traversal: ");


preorderTraversal(root);
printf("\n");

printf("Postorder Traversal: ");


postorderTraversal(root);
printf("\n");

printf("Tree Visualization:\n");
visualizeTree(root, 0);

return 0;
}

You might also like