Binary Tree Implement_ Array LL
Binary Tree Implement_ Array LL
• Left child = 2 * i + 1
• Right child = 2 * i + 2
• Parent = (i - 1) / 2
int tree[SIZE];
// Main menu
int main() {
int choice;
By Mr. Rahamatulla Assistant Professor,CSE,BWU.
initTree();
while (1) {
printf("\n--- Binary Tree Menu ---\n");
printf("1. Insert Node\n");
printf("2. Display Tree\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
insertNode();
break;
case 2:
displayTree();
break;
case 3:
return 0;
default:
printf("Invalid choice. Try again.\n");
}
}
return 0;
}
Sample Run:
mathematica
CopyEdit
--- Binary Tree Menu ---
1. Insert Node
2. Display Tree
3. Exit
Enter your choice: 1
Enter node value: 10
Enter index to insert at: 0
Node inserted at index 0.
#include <stdio.h>
#include <stdlib.h>
if (root == NULL) {
printf("Node %d inserted as root.\n", data);
return newNode;
}
printf("Insert %d to the left or right of node %d? (l/r): ", data, root->data);
scanf(" %c", &choice);
if (choice == 'l') {
root->left = insert(root->left);
} else if (choice == 'r') {
root->right = insert(root->right);
} else {
printf("Invalid choice.\n");
}
return root;
}
// Inorder traversal
void inorder(Node* root) {
if (root == NULL) return;
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
while (1) {
printf("\n--- Binary Tree Menu ---\n");
printf("1. Insert Node\n");
printf("2. Display Inorder Traversal\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
root = insert(root);
break;
case 2:
printf("Inorder Traversal: ");
inorder(root);
printf("\n");
break;
case 3:
return 0;
default:
printf("Invalid choice. Try again.\n");
}
}
}
Sample Interaction:
mathematica
CopyEdit
--- Binary Tree Menu ---
1. Insert Node
2. Display Inorder Traversal
3. Exit
Enter your choice: 1
Enter data: 10
Node 10 inserted as root.
return root;
}
int main() {
Node* root = NULL;
int choice, value;
while (1) {
printf("\n--- Binary Search Tree Menu ---\n");
printf("1. Insert Value\n");
printf("2. Display Inorder Traversal\n");
printf("3. Exit\n");
printf("Enter your choice: ");
switch (choice) {
case 1:
printf("Enter value to insert: ");
scanf("%d", &value);
root = insert(root, value);
break;
case 2:
printf("Inorder Traversal: ");
inorder(root);
printf("\n");
break;
case 3:
printf("Exiting program.\n");
return 0;
default:
printf("Invalid choice. Try again.\n");
}
}
return 0;
}
Sample Output
mathematica
CopyEdit
--- Binary Search Tree Menu ---
1. Insert Value
2. Display Inorder Traversal
3. Exit
Enter your choice: 1
Enter value to insert: 50