Question
Write a program in c that opens a file of integers and generates a binary tree using that data. The file format will be one
Write a program in c that opens a file of integers and generates a binary tree using that data. The file format will be one integer per line. The file will be called hw9.data. As you generate the tree you must also create a linked list that POINTS to the same nodes. Your code must do a pre-, in-, and post-order traversal of the tree and a traversal of the linked list. These must be four seperate functions. Your program must also correctly free all links of the tree and list on termination. This MUST be a seperate function.
__________________________________________________________________________________________________________________________________________________
Code so Far:
#include #include #include
struct myTree { int val; struct myTree *right, *left; };
typedef struct myTree _node;
void insert(_node*(*tree), _node* item) { if (!(*tree)) { *tree = item; return; } if (item->val < (*tree)->val) insert(&(*tree)->left, item);
else if (item->val > (*tree)->val) insert(&(*tree)->right, item); } void traverse(_node* tree) { if (tree->left != NULL) traverse(tree->left); printf("%d ", tree->val); if (tree->right != NULL) traverse(tree->right); } void postorder(_node* tree) { if (tree->left != NULL) postorder(tree->left); if (tree->right != NULL) postorder(tree->right); printf("%d ", tree->val); } void preorder(_node* tree) { printf("%d ", tree->val); if (tree->left != NULL) preorder(tree->left); if (tree->right != NULL) preorder(tree->right); } void main() { _node *current, *root; int i; int x; root = NULL;
for (i = 0; i <= 6; i++) { current = (_node*)malloc(sizeof(_node)); current->left = current->right = NULL; printf(" Enter a value for the tree "); scanf("%d",&x); current->val = x; insert(&root, current); } printf(" Inorder traversal "); traverse(root); printf(" Preorder traversal "); preorder(root); printf(" Postorder traversal "); postorder(root);
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started