Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdlib.h>
- using namespace std;
- struct Node
- {
- int data;
- int height;
- Node* left;
- Node* right;
- Node* parent;
- Node( int val )
- {
- this->data = val;
- left = right = parent = NULL;
- height = 1;
- }
- };
- Node* addData( Node* node, int value, Node* parent )
- {
- if ( node == NULL )
- {
- Node* newNode = new Node( value );
- if ( parent == NULL )
- newNode->parent = NULL;
- else
- newNode->parent = parent;
- return newNode;
- }
- if ( value < node->data )
- node->left = addData( node->left, value, node );
- else if ( value > node->data )
- node->right = addData( node->right, value, node );
- else
- {
- printf( "Data cannot be duplicated!!\n" );
- return node;
- }
- return node;
- }
- void preOrder( Node* node )
- {
- if ( node == NULL )
- return;
- // Algorithm of preOrder: VLR
- cout << node->data << " "; // visit
- preOrder( node->left ); // left node
- preOrder( node->right ); // right node
- }
- int main()
- {
- short option;
- Node* root = NULL;
- int x;
- do
- {
- system( "CLS" );
- printf( "Menu\n" );
- printf( "1. Insert data to tree\n" );
- printf( "2. Search data\n" );
- printf( "3. Delete data from tree - deletion by Merging\n" );
- printf( "4. Delete data from tree - deletion by Copying\n" );
- printf( "5. Pre-order traversal\n" );
- printf( "6. Post-order traversal\n" );
- printf( "7. In-order traversal\n" );
- printf( "8. Binary Search Tree\n" );
- printf( "9. Delete Leaf\n" );
- printf( "10. Delete Node with one child\n" );
- printf( "0. exit\n\n" );
- printf( "Your choice : " );
- scanf( "%d", &option );
- int i = 0;
- switch ( option )
- {
- case 0:
- printf( "Thank you for using this program!\n" );
- exit(0);
- break;
- case 1:
- // Input data: 50 25 75 10 35 60 85 5 15 30 40 55 65 80 90
- printf( "Input Data, to end, press 0\n\n" );
- do
- {
- printf( "Input data-%d : ", ++i );
- scanf( "%d", &x );
- } while( x > 0 );
- root = addData( root, x, NULL );
- printf( "\nInput Data Process is Finish!\n" );
- break;
- case 5:
- printf( "Pre Order Traversal: " );
- preOrder( root ); // BUG: always shows 0. Why??
- printf( "\n\n" );
- break;
- default:
- break;
- }
- } while ( option != 0 );
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement