DS4-3

//BCA Support //www.bcasupport.xyz #include <iostream.h> #include <conio.h> struct tree { int data; tree *left,*right; }*root,*leaf,*temp; int ch,data; int create(); int insert(tree *,int); int travel(); int preorder(tree *); int inorder(tree *); int postorder(tree *); int main() { while(1) { clrscr(); cout<<"\n===Tree===\n1. Creation\n2. Insertion" "\n3. Traversal\n4. Exit\nEnter choice : "; cin>>ch; switch(ch) { case 1: create(); break; case 2: if(root==NULL) { cout<<"\n\nTree doesn't exists"; getch(); break; } else { cout<<"\nEnter data : "; cin>>data; insert(root,data); cout<<"\nData inserted"; getch(); break; } case 3: travel(); break; default: return 0; } } } int create() { if(root==NULL) { clrscr(); root=(struct tree *)new tree; cout<<"\nTree created!\n\nEnter root data : "; cin>>root->data; root->left=NULL; root->right=NULL; } else { cout<<"\n\nTree already exists"; getch(); } return 0; } int insert(tree *node,int data) { clrscr(); if(data<=node->data) { if(node->left==NULL) { node->left=(struct tree *)new tree; node=node->left; node->data=data; node->left=NULL; node->right=NULL; } else insert(node->left,data); } else if(data>=node->data) { if(node->right==NULL) { node->right=(struct tree *)new tree; node=node->right; node->data=data; node->left=NULL; node->right=NULL; } else insert(node->right,data); } return 0; } int travel() { if(root==NULL) { cout<<"\n\nTree doesn't exists"; getch(); return 0; } clrscr(); cout<<"\n1. Preorder\n2. Inorder\n3. Postorder\nEnter choice : "; cin>>ch; cout<<"\nData-\n"; switch(ch) { case 1: preorder(root); break; case 2: inorder(root); break; case 3: postorder(root);break; default: cout<<"\n\nInvalid input"; getch(); return 0; } getch(); return 0; } int preorder(tree *node) { if(node==NULL) return 0; cout<<node->data<<" "; preorder(node->left); preorder(node->right); return 0; } int inorder(tree *node) { if(node==NULL) return 0; inorder(node->left); cout<<node->data<<" "; inorder(node->right); return 0; } int postorder(tree *node) { if(node==NULL) return 0; postorder(node->left); postorder(node->right); cout<<node->data<<" "; return 0; }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.