A ‘C’ program to read ‘n’ integers and store them in a Binary search tree structure and display the nodes level wise.
Binary search tree source code
#includetypedef struct node { int value; struct node * right; struct node * left; } mynode; mynode * root; void add_node(int value); void levelOrderTraversal(mynode * root); void main() { int num; char ch = ’y’; clrscr(); root = NULL; do { printf(“\nenter the node value”); scanf(“ % d”, & num); add_node(num); printf(“\ndo you want to continue (y / n)”); flushall(); scanf(“ % c”, & ch); } while (ch != ’n’); printf(“\n\ n\ nLEVEL ORDER TRAVERSAL\ n\ n”); levelOrderTraversal(root); getch(); } // Function to add a new node… void add_node(int value) { mynode * prev, * cur, * temp; temp = (mynode * ) malloc(sizeof(mynode)); temp - > value = value; temp - > right = NULL; temp - > left = NULL; if (root == NULL) { printf(“\nCreating the root..\n”); root = temp; return; } prev = NULL; cur = root; while (cur != NULL) { prev = cur; cur = (value < cur - > value) ? cur - > left : cur - > right; } if (value < prev - > value) prev - > left = temp; else prev - > right = temp; } // Level order traversal.. void levelOrderTraversal(mynode * root) { mynode * queue[100] = { (mynode * ) 0 }; // Important to initialize! int size = 0; int queue_pointer = 0; while (root) { printf(“[ % d]“, root - > value); if (root - > left) { queue[size++] = root - > left; } if (root - > right) { queue[size++] = root - > right; } root = queue[queue_pointer++]; } }
Output
enter the node value5
Creating the root..
do you want to continue (y/n)y
enter the node value7
do you want to continue (y/n)y
enter the node value3
do you want to continue (y/n)y
enter the node value10
do you want to continue (y/n)y
enter the node value2
do you want to continue (y/n)n
LEVEL ORDER TRAVERSAL
[5] [3] [7] [2] [10]
0 comments:
Post a Comment