Thread 1: EXC_BAD_ACCESS - c

I wrote binary search tree by C language, which data is string, and I have problem when I tried to type data.
Error show on line 14, I think root->data is NULL cause it, but I don't know how to solve.
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node {
Node *parent;
Node *left;
Node *right;
char *data;
};
Node *insert(Node *root, char *data) {
if (root == NULL) {
Node *tmp;
tmp = (Node *)malloc(sizeof(Node));
root->data = data; // <--- Line 14
tmp -> left = tmp -> right = NULL;
return tmp;
}
if (strcmp(data, root->data) > 0) {
root -> right = insert(root->right, data);
} else if (strcmp(data, root->data) < 0) {
root -> left = insert(root->left, data);
}
return root;
}
void Print(Node *root){
if (root == NULL) return;
Print(root->left);
printf("%s\n", root->data);
Print(root->right);
}
int main() {
Node *root = NULL;
char input[21];
while (scanf("%s", input) != EOF) {
root = insert(root, input);
}
Print(root);
return 0;
}

In your function:
Node *insert(Node *root, char *data) {
if (root == NULL) {
Node *tmp; // is this really needed?
tmp = (Node *)malloc(sizeof(Node)); // did your mean root = malloc(..) ?
root->data = data; // <--- root is always NULL, from test above
/* ... */

Related

How to prevent the program to display the converted input, I'm wanting the program to display the original input

I want my code to display the original input 3 -> 2-> 1-> and not display the reversed one.
The output is displaying the 1-> 2-> 3-> . I want to see the original input without ruining the codes. How can I do that? Our professor taught us the concept of linked list and it is connected in this program to input a number and check if it is a palendrome
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
void insertNum(struct node** head, int number) {
struct node* temp = malloc(sizeof(struct node));
temp -> data = number;
temp -> next = *head;
*head = temp;
}
void display(struct node* head) {
struct node* printNode = head;
printf("displaying list1...\n");
printf("displaying the converted list..\n");
while (printNode != NULL) {
if (printNode->next)
printf("%d->",printNode->data);
else
printf("%d->NULL\n",printNode->data);
printNode=printNode->next;
}
}
struct node* reverseLL(struct node* head) {
struct node* reverseNode = NULL, *temp;
if (head == NULL) {
printf("\nThe list is empty.\n\n");
exit(0);
}
while (head != NULL) {
temp = (struct node*) malloc(sizeof(struct node));
temp -> data = head -> data;
temp -> next = reverseNode;
reverseNode = temp;
head = head -> next;
}
return reverseNode;
}
int check(struct node* LLOne, struct node* LLTwo) {
while (LLOne != NULL && LLTwo != NULL) {
if (LLOne->data != LLTwo->data)
return 0;
LLOne = LLOne->next;
LLTwo = LLTwo->next;
}
return (LLOne == NULL && LLTwo == NULL);
}
void deleteList(struct node** display) {
struct node* temp = *display;
while (temp != NULL) {
temp = temp->next;
free(*display);
*display = temp;
}
}
int main() {
int inputNum, countRun = 0, loop;
char choice;
struct node* reverseList;
struct node* head = NULL;
do {
printf("%Run number : %d\n", ++countRun);
printf("Enter 0 to stop building the list, else enter any integer\n");
printf("Enter list to check whether it is a palindrome... \n");
do {
scanf("%d", &inputNum);
if (inputNum == 0)
break;
insertNum(&head, inputNum);
} while (inputNum != 0);
display(head);
reverseList = reverseLL(head);
if ((check(head, reverseList)) == 1)
printf("\nPalindrome list.\n\n");
else
printf("\nNot palindrome.\n\n");
deleteList(&head);
} while (countRun != 2);
system("pause");
return 0;
}
Your insertNum inserts at the front of the list.
You need a version that appends at the back of the list:
void
appendNum(struct node **head, int number)
{
struct node *temp = malloc(sizeof(struct node));
struct node *cur;
struct node *prev;
temp->data = number;
// find tail of the list
prev = NULL;
for (cur = *head; cur != NULL; cur = cur->next)
prev = cur;
// append after the tail
if (prev != NULL)
prev->next = temp;
// insert at front (first time only)
else
*head = temp;
}
Here is the full code:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
void
appendNum(struct node **head, int number)
{
struct node *temp = malloc(sizeof(struct node));
struct node *cur;
struct node *prev;
temp->data = number;
// find tail of the list
prev = NULL;
for (cur = *head; cur != NULL; cur = cur->next)
prev = cur;
// append after the tail
if (prev != NULL)
prev->next = temp;
// insert at front (first time only)
else
*head = temp;
}
void
insertNum(struct node **head, int number)
{
struct node *temp = malloc(sizeof(struct node));
temp->data = number;
temp->next = *head;
*head = temp;
}
void
display(struct node *head)
{
struct node *printNode = head;
printf("displaying list1...\n");
printf("displaying the converted list..\n");
while (printNode != NULL) {
if (printNode->next)
printf("%d->", printNode->data);
else
printf("%d->NULL\n", printNode->data);
printNode = printNode->next;
}
}
struct node *
reverseLL(struct node *head)
{
struct node *reverseNode = NULL,
*temp;
if (head == NULL) {
printf("\nThe list is empty.\n\n");
exit(0);
}
while (head != NULL) {
temp = (struct node *) malloc(sizeof(struct node));
temp->data = head->data;
temp->next = reverseNode;
reverseNode = temp;
head = head->next;
}
return reverseNode;
}
int
check(struct node *LLOne, struct node *LLTwo)
{
while (LLOne != NULL && LLTwo != NULL) {
if (LLOne->data != LLTwo->data)
return 0;
LLOne = LLOne->next;
LLTwo = LLTwo->next;
}
return (LLOne == NULL && LLTwo == NULL);
}
void
deleteList(struct node **display)
{
struct node *temp = *display;
while (temp != NULL) {
temp = temp->next;
free(*display);
*display = temp;
}
}
int
main()
{
int inputNum, countRun = 0, loop;
char choice;
struct node *reverseList;
struct node *head = NULL;
do {
printf("%Run number : %d\n", ++countRun);
printf("Enter 0 to stop building the list, else enter any integer\n");
printf("Enter list to check whether it is a palindrome... \n");
do {
scanf("%d", &inputNum);
if (inputNum == 0)
break;
#if 0
insertNum(&head, inputNum);
#else
appendNum(&head, inputNum);
#endif
} while (inputNum != 0);
display(head);
reverseList = reverseLL(head);
if ((check(head, reverseList)) == 1)
printf("\nPalindrome list.\n\n");
else
printf("\nNot palindrome.\n\n");
deleteList(&head);
} while (countRun != 2);
system("pause");
return 0;
}

%s is skipping the entire print line - no user input

What's wrong in my code? I successfully created a tree and everything is working fine except printInorder function and print statement in void main. When I try to print with %s its skipping the entire line.
Can you please help me in resolving this? I even tried fflush but it doesn't help me in my case and I don't try any scanf statement in my code.
struct Tree
{
char data[10];
struct Tree *left;
struct Tree *right;
} * root;
struct Tree *createNode(char data[])
{
struct Tree *node = malloc(sizeof(struct Tree));
strcpy(node->data, data);
node->left = node->right = NULL;
insertTree(node, root, data);
}
void insertTree(struct Tree *currentNode, struct Tree *temp, char data[])
{
char fletter=data[0];
if (fletter=='a'||fletter=='e'||fletter=='o'||fletter=='i'||fletter=='u')
{
if (root == NULL)
{
root = currentNode;
printf("inserted at root");
}
else if (temp->left == NULL)
{
temp->left = currentNode;
printf("data inserted successfully at left");
}
else
{
insertTree(currentNode, temp->left,data);
}
}
else
{
if (root == NULL)
{
root = currentNode;
printf("inserted at root");
}
else if (temp->right == NULL)
{
temp->right = currentNode;
printf("data inserted successfully at right");
}
else
{
insertTree(currentNode, temp->right,data);
}
}
}
void printInorder(struct Tree *tmp)
{
if (tmp == NULL)
return;
printInorder(tmp->left);
printf("%s ",tmp->data);
printInorder(tmp->right);
}
void main()
{
struct Tree *root = createNode("saish");
struct Tree *d1 = createNode("ansha");
struct Tree *d2 = createNode("shish");
printf("%s",root->data);
printInorder(root);
}
createNode function doesn't return anything even though it is defined to do so.
void insertTree(struct Tree *currentNode, struct Tree *temp, char data[])
{
char fletter=data[0];
if (fletter=='a'||fletter=='e'||fletter=='o'||fletter=='i'||fletter=='u')
{
if (root == NULL)
{
root = currentNode;
printf("inserted at root");
}
else if (temp->left == NULL)
{
temp->left = currentNode;
printf("data inserted successfully at left");
}
else
{
insertTree(currentNode, temp->left,data);
return node;
}
}

How can I turn a tree into a string of bracket representation in C?

#include <stdio.h>
#include <stdlib.h>
typedef struct node_st {
int data;
struct node_st* left;
struct node_st* right;
};
void preorder(struct node_st *root) {
if (root != NULL) {
printf("%d\n", root->data);
preorder(root->left);
preorder(root->right);
}
}
void postorder(struct node_st *root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
printf("%d\n", root->data);
}
}
struct node_st* createNode(value) {
struct node_st* newNode = malloc(sizeof(struct node_st));
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct node_st* insertLeft(struct node_st* root, int value){
root->left = createNode(value);
return root->left;
}
struct node_st* insertRight(struct node_st* root, int value){
root->right = createNode(value);
return root->right;
}
int main() {
struct node_st* root = createNode(2);
insertLeft(root, 6);
insertRight(root, 9);
insertLeft(root->left, 2);
insertLeft(root->right, 1);
printf("\nPreorder\n");
preorder(root);
printf("\nPostorder\n");
postorder(root);
}
I need to make a function to store a tree into a string with bracket representation like (A(B)(C)) and to read it to make a tree, but I'm having trouble finding info online on how to do this in C, would appreciate any help.
The next step after this is to store it and read it from a file, but I can handle that with the documentation.
Here is code that prints the tree in bracketed representation. The format you request is ambiguous — if a node has only one child, you cannot tell whether that child is the left child or the right child. That ambiguous format is produced by the functions with _v1_ in the name: print_v1_tree(), print_v1_preorder(), print_v1_postorder(), print_v1_inorder().
There is an alternative format where an empty subtree is represented by () unless the node is a leaf node (both child nodes are null).
There's also a free_tree() function to release the memory for a tree.
#include <stdio.h>
#include <stdlib.h>
typedef struct node_st
{
int data;
struct node_st *left;
struct node_st *right;
} Node;
typedef void (*Print)(const Node *node);
extern struct node_st *createNode(int value);
extern struct node_st *insertLeft(struct node_st *root, int value);
extern struct node_st *insertRight(struct node_st *root, int value);
extern void postorder(struct node_st *root);
extern void preorder(struct node_st *root);
extern void inorder(struct node_st *root);
extern void print_v1_postorder(const Node *node);
extern void print_v1_inorder(const Node *node);
extern void print_v1_preorder(const Node *node);
extern void print_v1_tree(const char *tag, const Node *node, Print print);
extern void print_v2_postorder(const Node *node);
extern void print_v2_inorder(const Node *node);
extern void print_v2_preorder(const Node *node);
extern void print_v2_tree(const char *tag, const Node *node, Print print);
extern void free_tree(Node *node);
void preorder(struct node_st *root)
{
if (root != NULL)
{
printf("%d\n", root->data);
preorder(root->left);
preorder(root->right);
}
}
void postorder(struct node_st *root)
{
if (root != NULL)
{
postorder(root->left);
postorder(root->right);
printf("%d\n", root->data);
}
}
void inorder(struct node_st *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d\n", root->data);
inorder(root->right);
}
}
struct node_st *createNode(int value)
{
struct node_st *newNode = malloc(sizeof(struct node_st));
if (newNode == NULL)
{
fprintf(stderr, "Failed to allocate memory for a node\n");
exit(1);
}
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct node_st *insertLeft(struct node_st *root, int value)
{
root->left = createNode(value);
return root->left;
}
struct node_st *insertRight(struct node_st *root, int value)
{
root->right = createNode(value);
return root->right;
}
void print_v1_preorder(const Node *node)
{
printf("%d", node->data);
if (node->left != NULL)
{
putchar('(');
print_v1_preorder(node->left);
putchar(')');
}
if (node->right != NULL)
{
putchar('(');
print_v1_preorder(node->right);
putchar(')');
}
}
void print_v1_inorder(const Node *node)
{
if (node->left != NULL)
{
putchar('(');
print_v1_inorder(node->left);
putchar(')');
}
printf("%d", node->data);
if (node->right != NULL)
{
putchar('(');
print_v1_inorder(node->right);
putchar(')');
}
}
void print_v1_postorder(const Node *node)
{
if (node->left != NULL)
{
putchar('(');
print_v1_postorder(node->left);
putchar(')');
}
if (node->right != NULL)
{
putchar('(');
print_v1_postorder(node->right);
putchar(')');
}
printf("%d", node->data);
}
void print_v1_tree(const char *tag, const Node *node, Print print)
{
printf("%s: (", tag);
if (node != NULL)
(*print)(node);
putchar(')');
putchar('\n');
}
void print_v2_preorder(const Node *node)
{
if (node == NULL)
return;
printf("%d", node->data);
if (node->left != NULL || node->right != NULL)
{
putchar('(');
print_v2_preorder(node->left);
putchar(')');
}
if (node->right != NULL || node->left != NULL)
{
putchar('(');
print_v2_preorder(node->right);
putchar(')');
}
}
void print_v2_inorder(const Node *node)
{
if (node == NULL)
return;
if (node->left != NULL || node->right != NULL)
{
putchar('(');
print_v2_inorder(node->left);
putchar(')');
}
printf("%d", node->data);
if (node->right != NULL || node->left != NULL)
{
putchar('(');
print_v2_inorder(node->right);
putchar(')');
}
}
void print_v2_postorder(const Node *node)
{
if (node == NULL)
return;
if (node->left != NULL || node->right != NULL)
{
putchar('(');
print_v2_postorder(node->left);
putchar(')');
}
if (node->right != NULL || node->left != NULL)
{
putchar('(');
print_v2_postorder(node->right);
putchar(')');
}
printf("%d", node->data);
}
void print_v2_tree(const char *tag, const Node *node, Print print)
{
printf("%s: (", tag);
if (node != NULL)
(*print)(node);
putchar(')');
putchar('\n');
}
/* Must be post-order release, but could do right before left */
void free_tree(Node *node)
{
if (node != NULL)
{
free(node->left);
free(node->right);
free(node);
}
}
int main(void)
{
struct node_st *root = createNode(3);
insertLeft(root, 6);
insertRight(root, 9);
insertLeft(root->left, 2);
insertLeft(root->right, 1);
printf("\nPreorder\n");
preorder(root);
printf("\nPostorder\n");
postorder(root);
printf("\nInorder\n");
inorder(root);
printf("\nAmbiguous:\n");
print_v1_tree("Preorder", root, print_v1_preorder);
print_v1_tree("Inorder", root, print_v1_inorder);
print_v1_tree("Postorder", root, print_v1_postorder);
print_v1_tree("Empty", NULL, print_v1_inorder);
printf("\nUnambiguous:\n");
print_v2_tree("Preorder", root, print_v2_preorder);
print_v2_tree("Inorder", root, print_v2_inorder);
print_v2_tree("Postorder", root, print_v2_postorder);
print_v2_tree("Empty", NULL, print_v2_inorder);
insertRight(root->right, 13);
insertRight(root->left, 3);
insertRight(root->left->right, 4);
insertRight(root->left->right->right, 5);
printf("\nExtended tree - unambiguous:\n");
print_v2_tree("Preorder", root, print_v2_preorder);
print_v2_tree("Inorder", root, print_v2_inorder);
print_v2_tree("Postorder", root, print_v2_postorder);
print_v2_tree("Empty", NULL, print_v2_inorder);
free_tree(root);
return 0;
}
The output from this is:
Preorder
3
6
2
9
1
Postorder
2
6
1
9
3
Inorder
2
6
3
1
9
Ambiguous:
Preorder: (3(6(2))(9(1)))
Inorder: (((2)6)3((1)9))
Postorder: (((2)6)((1)9)3)
Empty: ()
Unambiguous:
Preorder: (3(6(2)())(9(1)()))
Inorder: (((2)6())3((1)9()))
Postorder: (((2)()6)((1)()9)3)
Empty: ()
Extended tree - unambiguous:
Preorder: (3(6(2)(3()(4()(5))))(9(1)(13)))
Inorder: (((2)6(()3(()4(5))))3((1)9(13)))
Postorder: (((2)(()(()(5)4)3)6)((1)(13)9)3)
Empty: ()
Converting this to store the data in a string is not too difficult. Parsing it is fiddlier — regardless of which format you use. Preorder may be the easiest to handle.
Here is my code for storing a tree in a string, using sprintf (return number of chars stored), given:
A node to begin storing (root on first call)
A pre alocated string, you can modify the code to realloc
The position on the string you are printing (i)
The max size of the string
int string_parenthesis_by_node(node_t *nd, char *str, int i, int max){
if (!nd) return 0;
// checks the size limit
int added = (ceil(log10(nd->key > 0 ? nd->key : 1)) + 2);
if (i + added >= max){
fprintf(stderr, "TOO LARGE INPUT TO BUFFER, tried to add %d on top of %d, maxing %d", added, i, max);
return 0;
}
// res is the current position you are storing
// it is incremented after every sprint
int res = i;
res += sprintf(str+res, "(%d", nd->key);
res += string_parenthesis_by_node(nd->left, str, res, max);
res += string_parenthesis_by_node(nd->right, str, res, max);
res += sprintf(str+res, ")");
return res-i;
}```

Deletion of node in Binary Search Tree is throwing error

Experts, this is my code of creation and deletion of nodes in Binary Search Tree. It's working fine for insertion, but throwing segmentation fault (core dumped) when trying to delete a node (on invoking deleteNode( ) function). I don't understand what's actually the problem. Please help! Thank you in advance!
#include <stdio.h>
#include <stdlib.h>
int size = 0;
typedef struct mylist{
int data;
struct mylist *left;
struct mylist *right;
}node;
node *root;
void create_root(node *root){
root = NULL;
}
//Inserting nodes
node* insert(node *root, int val){
node *ptr, *parentptr, *nodeptr;
ptr = (node*)malloc(sizeof(node));
ptr -> data = val;
ptr -> left = NULL;
ptr -> right = NULL;
if(root == NULL)
root = ptr;
else{
parentptr = NULL;
nodeptr = root;
while(nodeptr != NULL){
parentptr=nodeptr;
if(val < nodeptr -> data)
nodeptr = nodeptr -> left;
else
nodeptr = nodeptr -> right;
}
if(val < parentptr -> data)
parentptr -> left = ptr;
else
parentptr -> right = ptr;
}
return root;
}
node* minValueNode(node* root)
{
node* cur = root;
while (cur->left != NULL)
cur = cur->left;
return cur;
}
node* deleteNode(node* root, int key)
{
if (root == NULL){
printf("\nValue not found\n");
}
if (key < root-> data)
root->left = deleteNode(root->left, key);
else if (key > root-> data)
root->right = deleteNode(root->right, key);
else
{
if (root->left == NULL)
{
node *temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
node *temp = root->left;
free(root);
return temp;
}
node* temp = minValueNode(root->right); //Inorder successor
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}
void main(){
int option, val;
node *ptr;
int flag = 1;
create_root(root);
while(flag != 2){
printf("\nChoose-\n1-Insert\n2-Delete\n3-Exit\n");
scanf("%d", &option);
switch(option){
case 1:{
printf("\nEnter the value of new node\n");
size++;
scanf("%d", &val);
root = insert(root, val);
break;
}
case 2:{
int k;
printf("Enter the value to delete");
scanf("%d",&k);
root=deleteNode(root, k);
size--;
break;
}
case 3:
flag=2;
break;
default:
printf("\nWrong entry\n");
}
}
}
You must either return NULL in the first if() in deleteNode(), or you must put an else before the second if()
node* deleteNode(node* root, int key)
{
if (root == NULL){
printf("\nValue not found\n");
return NULL; // <== This was missing.
}
...
}
or alternatively (perhaps intended?):
node* deleteNode(node* root, int key)
{
if (root == NULL){
printf("\nValue not found\n");
}
else if(key < root->data)
...
}
At the moment this falls through to the next if(key < root->data) even when root is null, which causes the segfault.
Also: Use nullptr if you can use C++11.

Binary Tree Level Order Traversal Using Queue in C

I am fairly new to C. I started studying data structures and was okay with linked lists, stacks, and queues. Right now I am implementing BST's and they seem to be pretty complicated. Here I tried writing code for Level Order Transversal and I am not getting the required output.
Please help me fix it. It showed no errors. On running the program, I get infinite 'G' as my output. I expected to get all the characters (which I had input in the main function) to be printed in some order.
#include <stdio.h>
#include <stdlib.h>
struct Node
{
char data;
struct Node* right;
struct Node* left;
};
void enq(struct Node* temproot);
struct Node* deq();
struct Node* Insert(struct Node* ,char x);
struct Node* newNode (char data);
void LevelOrder(struct Node* root);
struct Node* front = NULL;
struct Node* rear = NULL;
int main()
{
struct Node* root;
root = NULL;
root = Insert(root,'F');
root = Insert(root,'B');
root = Insert(root,'C');
root = Insert(root,'D');
root = Insert(root,'E');
root = Insert(root,'G');
root = Insert(root,'A');
root = Insert(root,'H');
root = Insert(root,'I');
LevelOrder(root);
return 0;
}
struct Node* Insert(struct Node* root,char x)
{
if (root == NULL)
{
root = newNode(x);
}
else if (x <= root->data)
{
root->left = Insert(root->left, x);
}
else
{
root->right = Insert(root->right,x);
}
return root;
}
struct Node* newNode(char x)
{
struct Node* temp1 = (struct Node*)malloc(sizeof(struct Node));
temp1->data = x;
temp1->right = NULL;
temp1->left = NULL;
return temp1;
}
void enq(struct Node* temproot)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = temproot->data;
temp->right = temp->left= NULL;
if(front == NULL && rear == NULL)
{
front = rear = temp;
return;
}
rear->right = temp;
rear = temp;
}
struct Node* deq()
{
struct Node* temp = front;
if (front == NULL)
{
printf("The queue is empty!");
}
else if (rear == front)
{
front = rear = NULL;
}
else
{
front = front->right;
}
return temp;
}
void LevelOrder(struct Node* root)
{
struct Node* temproot = root;
while(temproot != NULL)
{
printf("%c ", temproot->data);
if(temproot->left != NULL)
{enq(temproot->left);
}
if (temproot->right !=NULL)
{enq(temproot->right);
}
temproot = deq();
}
}
As noted in the comments, you need to enqueue the pointers to the nodes in the tree structures — not the data. You can do this by using the left element to point to the node and the right element to point to the next item in the queue.
In the comments, I said:
I've not tested it, but maybe (just maybe), you need to replace
temp->data = temproot->data;
temp->right = temp->left= NULL;
in enq() with
temp->left = temproot;
temp->right = NULL;
and then in deq() you should have
struct Node *next = temp->left;
free(temp);
return next;
This seems to be the correct prescription. This code has a function dump_BST that dumps the data in the tree for debugging purposes (and an auxilliary function dump_BST_node() that implements a pre-order traversal while printing.
#include <stdio.h>
#include <stdlib.h>
struct Node
{
char data;
struct Node *right;
struct Node *left;
};
void enq(struct Node *temproot);
struct Node *deq(void);
struct Node *Insert(struct Node *, char x);
struct Node *newNode(char data);
void LevelOrder(struct Node *root);
void dump_BST(const char *tag, const struct Node *node);
struct Node *front = NULL;
struct Node *rear = NULL;
int main(void)
{
struct Node *root = NULL;
dump_BST("Empty", root);
root = Insert(root, 'F');
dump_BST("Added F", root);
root = Insert(root, 'B');
dump_BST("Added B", root);
root = Insert(root, 'C');
//dump_BST("Added C", root);
root = Insert(root, 'D');
//dump_BST("Added D", root);
root = Insert(root, 'E');
//dump_BST("Added E", root);
root = Insert(root, 'G');
//dump_BST("Added G", root);
root = Insert(root, 'A');
//dump_BST("Added A", root);
root = Insert(root, 'H');
//dump_BST("Added H", root);
root = Insert(root, 'I');
dump_BST("Added I", root);
LevelOrder(root);
return 0;
}
struct Node *Insert(struct Node *root, char x)
{
if (root == NULL)
{
root = newNode(x);
}
else if (x <= root->data)
{
root->left = Insert(root->left, x);
}
else
{
root->right = Insert(root->right, x);
}
return root;
}
struct Node *newNode(char x)
{
struct Node *temp1 = (struct Node *)malloc(sizeof(struct Node));
temp1->data = x;
temp1->right = NULL;
temp1->left = NULL;
return temp1;
}
void enq(struct Node *temproot)
{
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp->right = NULL;
temp->left = temproot;
temp->data = 'Z';
if (front == NULL && rear == NULL)
{
front = rear = temp;
}
else
{
rear->right = temp;
rear = temp;
}
}
struct Node *deq(void)
{
struct Node *temp = front;
if (front == NULL)
{
printf("The queue is empty!\n");
}
else if (rear == front)
{
front = rear = NULL;
}
else
{
front = front->right;
}
struct Node *next = (temp == NULL) ? NULL : temp->left;
free(temp);
return next;
}
void LevelOrder(struct Node *root)
{
struct Node *temproot = root;
while (temproot != NULL)
{
printf("%c ", temproot->data);
if (temproot->left != NULL)
{
enq(temproot->left);
}
if (temproot->right != NULL)
{
enq(temproot->right);
}
temproot = deq();
}
putchar('\n');
}
static void dump_BST_nodes(const struct Node *node)
{
if (node != NULL)
{
printf("Node: '%c' (ptr = %p, left = %p, right = %p)\n",
node->data, (void *)node, (void *)node->left, (void *)node->right);
dump_BST_nodes(node->left);
dump_BST_nodes(node->right);
}
}
void dump_BST(const char *tag, const struct Node *node)
{
printf("%s:\n", tag);
dump_BST_nodes(node);
printf("%s: end\n", tag);
}
When run, this produces:
Empty:
Empty: end
Added F:
Node: 'F' (ptr = 0x7fc63fc02750, left = 0x0, right = 0x0)
Added F: end
Added B:
Node: 'F' (ptr = 0x7fc63fc02750, left = 0x7fc63fc02770, right = 0x0)
Node: 'B' (ptr = 0x7fc63fc02770, left = 0x0, right = 0x0)
Added B: end
Added I:
Node: 'F' (ptr = 0x7fc63fc02750, left = 0x7fc63fc02770, right = 0x7fc63fc027f0)
Node: 'B' (ptr = 0x7fc63fc02770, left = 0x7fc63fc02810, right = 0x7fc63fc02790)
Node: 'A' (ptr = 0x7fc63fc02810, left = 0x0, right = 0x0)
Node: 'C' (ptr = 0x7fc63fc02790, left = 0x0, right = 0x7fc63fc027b0)
Node: 'D' (ptr = 0x7fc63fc027b0, left = 0x0, right = 0x7fc63fc027d0)
Node: 'E' (ptr = 0x7fc63fc027d0, left = 0x0, right = 0x0)
Node: 'G' (ptr = 0x7fc63fc027f0, left = 0x0, right = 0x7fc63fc02830)
Node: 'H' (ptr = 0x7fc63fc02830, left = 0x0, right = 0x7fc63fc02850)
Node: 'I' (ptr = 0x7fc63fc02850, left = 0x0, right = 0x0)
Added I: end
F B G A C H D I E The queue is empty!
You'll need to clean up the code — the message that the queue is empty is a nuisance, and you won't need the debugging printing. But that does show how I did go about checking the code (the fact that it worked OK the first time through was an unexpected but pleasant bonus).

Resources