Hello:
I am trying to finish an assignment in my class, and I have the code all typed out with no errors that keep it from compiling, but when I run it, the functions do not seem to add values to the tree. I just want some pointers (no pun intended) on what problems I am having, so I can correct the code. Any help would be greatly appreciated!!
binaryTree.h:
Code:
struct Node
{
int val;
struct Node *left;
struct Node *right;
};
int SearchTree(struct Node *start, int query);
struct AddNode(struct Node *newnode, int value);
int PrintTree(struct Node *begin);
main.c:
Code:
#include <stdio.h>
#include <stdlib.h>
#include "binaryTree.h"
int main()
{
char decision;
int newnum;
int findnum;
int firstnum;
int i;
struct Node *root;
root=malloc(sizeof(struct Node));
for(i=0; i>=0; i++)
{
if(i==0)
{
printf("Enter the number for the beginning of the tree:");
scanf("%d", &firstnum);
printf("\n");
root->val = firstnum;
root->left = NULL;
root->right = NULL;
}
printf("===========================\n");
printf("a to add a value\n");
printf("s to search for a value\n");
printf("l to list all stored values\n");
printf("e to exit program\n");
printf("Enter your choice:");
scanf("%c", &decision);
if(decision == 'e' || decision == 'E')
return 0;
while(decision != 'a' && decision != 's' && decision != 'l' && decision != 'A' && decision != 'S' && decision != 'L')
{
printf("\nThat is not a valid choice.\n");
printf("===========================\n");
printf("a to add a value\n");
printf("s to search for a value\n");
printf("l to list all stored values\n");
printf("Enter your choice:");
scanf("%c", &decision);
printf("\n");
if(decision == 'e' || decision == 'E')
return 0;
}
if(decision == 'a' || decision == 'A')
{
printf("\nEnter the value to add:");
scanf("%d", &newnum);
printf("\n");
AddNode(root, newnum);
}
if(decision == 's' || decision == 'S')
{
printf("\nEnter the value to search for:");
scanf("%d", &findnum);
printf("\n");
SearchTree(root, findnum);
}
if(decision == 'l' || decision == 'L')
PrintTree(root);
}
return 0;
}
binaryTree.c:
Code:
#include <stdio.h>
#include <stdlib.h>
#include "binaryTree.h"
int SearchTree(struct Node *start, int query)
{
if (start == NULL)
{
printf("%d was not found.", query);
return(-1);
}
else
{
if (query == start->val)
{
printf("%d was found.", query);
return(0);
}
else
{
if (query < start->val)
return SearchTree(start->left, query);
else
return SearchTree(start->right, query);
}
}
}
struct AddNode(struct Node *newnode, int value)
{
if (newnode == NULL)
{
struct Node *newnode = malloc(sizeof(struct Node));
newnode->val = value;
newnode->left = NULL;
newnode->right = NULL;
return(newnode);
}
else
{
if (value < newnode->val)
newnode->left = AddNode(newnode->left, value);
else
newnode->right = AddNode(newnode->right, value);
return (newnode);
}
}
int PrintTree(struct Node *begin)
{
if (begin == NULL)
return 0;
PrintTree(begin->left);
printf("%d \n", begin->val);
PrintTree(begin->right);
return 0;
}