Skip to main content

19. Write a c program for create a binary tree and its operation.

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
int data;
struct node *left;
struct node *right;
} Node;

Node *createNode(int data) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

Node *insert(Node *root, int data) {
if (root == NULL) {
root = createNode(data);
} else if (data <= root->data) {
root->left = insert(root->left, data);
} else {
root->right = insert(root->right, data);
}
return root;
}

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

int main() {
Node *root = NULL;
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);

printf("Inorder traversal of the binary tree is: \\n");
inorder(root);

return 0;
}

Output

d