Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- /**
- Defining a node
- **/
- struct node {
- char data;
- struct node *left;
- struct node *right;
- };
- typedef struct node Node;
- /// Tree construction
- Node* new_node ( char );
- /*** BST only functions **/
- Node* search ( Node*, char );
- Node* insert ( Node*, char );
- /**
- Dept first search
- **/
- /// Dept first search in order
- void dfs_in_order ( Node* );
- /// Dept first search pre order
- void dfs_pre_order ( Node* );
- /// Dept first search post order
- void dfs_post_order ( Node* );
- int main ( void )
- {
- Node *root = new_node( 'H' );
- insert ( root, 'B' );
- insert ( root, 'Z' );
- insert ( root, 'D' );
- insert ( root, 'F' );
- insert ( root, 'C' );
- printf ( "DFS Pre order: \n" );
- dfs_pre_order( root );
- printf ( "\nDFS In order: \n" );
- dfs_in_order( root );
- printf ( "\nDFS Post order: \n" );
- dfs_post_order( root );
- return 0;
- }
- Node* search ( Node* tree, char data ) {
- if ( tree == NULL || tree->data == data )
- return tree;
- if ( data > tree->data )
- return search ( tree->right, data );
- return search ( tree->left, data );
- }
- Node* new_node ( char data ) {
- Node *new_node = ( Node* ) malloc ( sizeof ( Node ) );
- new_node->data = data;
- new_node->left = NULL;
- new_node->right = NULL;
- return new_node;
- }
- Node* insert ( Node* tree, char data ) {
- if ( tree == NULL ) return new_node( data );
- if ( tree->data < data )
- tree->left = insert ( tree->left, data );
- if ( tree->data > data )
- tree->right = insert ( tree->right, data );
- return tree;
- }
- void dfs_in_order ( Node *tree ) {
- /// Root
- if ( tree == NULL )
- return;
- /// Left subtree
- dfs_in_order( tree->left );
- printf ( "%c ", tree->data );
- /// Right subtree
- dfs_in_order( tree->right );
- }
- void dfs_pre_order ( Node *tree ) {
- /// Root
- if ( tree == NULL )
- return;
- printf ( "%c ", tree->data );
- /// Left subtree
- dfs_pre_order( tree->left );
- /// Right subtree
- dfs_pre_order( tree->right );
- }
- void dfs_post_order ( Node *tree ) {
- /// Root
- if ( tree == NULL )
- return;
- /// Left subtree
- dfs_post_order( tree->left );
- /// Right subtree
- dfs_post_order( tree->right );
- printf ( "%c ", tree->data );
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement