0% found this document useful (0 votes)
11 views

#Include Using Namespace #Include Struct

This C++ code defines a binary search tree data structure and provides functions to insert nodes into the tree, traverse the tree using inorder traversal, and display a menu to add nodes or display the tree. It defines a node struct with left, data, and right pointers, and global root and parent pointers. The insert function adds a new node by dynamically allocating memory, setting the data, and recursively searching for the correct position to insert based on data values. The inorder function recursively traverses and prints the tree values. The main function displays a menu and calls insert or inorder based on user input.

Uploaded by

Jarvis Anderson
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

#Include Using Namespace #Include Struct

This C++ code defines a binary search tree data structure and provides functions to insert nodes into the tree, traverse the tree using inorder traversal, and display a menu to add nodes or display the tree. It defines a node struct with left, data, and right pointers, and global root and parent pointers. The insert function adds a new node by dynamically allocating memory, setting the data, and recursively searching for the correct position to insert based on data values. The inorder function recursively traverses and prints the tree values. The main function displays a menu and calls insert or inorder based on user input.

Uploaded by

Jarvis Anderson
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include<iostream> using namespace std; #include<conio.

h> struct node { node *left; int data; node *right; }; node *root=NULL; node *parent; void insert() { node *temp=new node; cout<<"enter data for new node"; cin>>temp->data; temp->left=NULL; temp->right=NULL; if(root==NULL) //is tree empty?? root=temp; else// if tree is not empty { node *child=root;// point the top of the tree while(child!=NULL) // untill you get empty space { parent=child;// B4 moving save the current memory (parent) if(temp->data>child->data) child=child->right; //move to next(child) else child=child->left; } if(temp->data>parent->data) parent->right=temp; else parent->left=temp;

} void inorder(node *n) { if(n==NULL)//base function return; else { /// recursive function inorder(n->left); cout<<n->data<<" , "; inorder(n->right); } } void main() { while(1) { int ch; cout<<"enter 1 to add data in the tree"<<endl; cout<<"enter 2 to show the values by inorder traversal"<<endl; cin>>ch; switch(ch) { case 1: insert(); break; case 2: inorder(root); break; } } }

You might also like