#include <iostream>
#include <string.h>
#include <stdlib.h>
#pragma warning(disable : 4996)
#define MaxWordSize 100
// Declare a structure that holds data in a node
typedef struct {
char word[MaxWordSize + 1];
} NodeData;
typedef struct treeNode {
NodeData data;
struct treeNode* left, * right;
} TreeNode, *TreeNodePtr;
typedef struct {
TreeNodePtr root;
} BinaryTree;
TreeNodePtr buildTree(FILE *in) {
char str[MaxWordSize + 1];
//read one word from the file
fscanf_s (in, "%s", str);
//if we see @ then return null (end of current recursion)
if (strcmp (str, "@") == 0) return NULL;
//allocate space for a TreeNode
TreeNodePtr p = (TreeNodePtr) malloc (sizeof(TreeNode));
// copy the data to the tree node
strcpy_s (p->data.word, str);
// build the left sub tree using recursion
p->left = buildTree(in);
// build the right sub tree using recursion
p->right = buildTree(in);
return p;
} //end buildTree
// traverse the tree in in-order basis
// print the treee content in in-order basis
void inOrder(TreeNodePtr node) {
//printf("%s ", node->data.word);
if (node != NULL) {
inOrder(node->left);
printf("%s ", node->data.word);
inOrder(node->right);
}
} //end inOrder
// main method
int main(){
// declare a binary tree
BinaryTree bt;
//open the file where tree data are kept
FILE *in = fopen("btree.in", "r");
// build the tree
bt.root = buildTree(in);
inOrder(bt.root);
}
Jul 20