exp 9: init

Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
This commit is contained in:
2022-12-27 20:25:35 +05:30
parent 8fdaad7037
commit 4ee6a026bf
3 changed files with 93 additions and 0 deletions

93
9.c Normal file
View File

@@ -0,0 +1,93 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Car car;
typedef struct Node node;
struct Node {
char type[30];
char company[50];
uint yom;
struct Node *left;
struct Node *right;
};
node *new (char *type, char *company, uint yom) {
node *n = malloc(sizeof(node));
n->left = n->right = NULL;
strcpy(n->type, type);
strcpy(n->company, company);
n->yom = yom;
return n;
}
void insert(node **root, char *type, char *company, uint yom) {
if (!(*root)) {
*root = new (type, company, yom);
return;
}
if (yom < (*root)->yom)
insert(&((*root)->left), type, company, yom);
else
insert(&((*root)->right), type, company, yom);
}
void preorder(node *n) {
if (!n)
return;
printf("Type: %s\nCompany: %s\nYear: %d\n", n->type, n->company, n->yom);
preorder(n->left);
preorder(n->right);
}
void postorder(node *n) {
if (!n)
return;
postorder(n->left);
postorder(n->right);
printf("Type: %s\nCompany: %s\nYear: %d\n", n->type, n->company, n->yom);
}
void inorder(node *n) {
if (!n)
return;
inorder(n->left);
printf("Type: %s\nCompany: %s\nYear: %d\n", n->type, n->company, n->yom);
inorder(n->right);
}
void free_tree(node *n) {
if (!n)
return;
free_tree(n->left);
free_tree(n->right);
free(n);
}
int main() {
node *root = NULL;
insert(&root, "A", "Amaang", 4004);
insert(&root, "Sahi", "Vivek", 2003);
insert(&root, "How", "Alphonso", 9999);
printf("---------\n");
printf("Preorder:\n");
printf("---------\n");
preorder(root);
printf("---------\n");
printf("Postorder:\n");
printf("---------\n");
postorder(root);
printf("---------\n");
printf("Inorder:\n");
printf("---------\n");
inorder(root);
free_tree(root);
}