Created
June 24, 2012 11:11
-
-
Save iporsut/2982846 to your computer and use it in GitHub Desktop.
Pre to Post order Binary Search Tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
typedef struct _btree { | |
int n; | |
struct _btree *left; | |
struct _btree *right; | |
}BTree; | |
BTree * createNode() { | |
BTree *node = (BTree*) malloc(sizeof(BTree)); | |
node->left = node->right = NULL; | |
return node; | |
} | |
void read_preorder(int data,BTree **root) { | |
if (*root == NULL) { | |
*root = createNode(); | |
(*root)->n = data; | |
} else | |
if (data < (*root)->n) { | |
if ((*root)->left !=NULL) { | |
read_preorder(data,&((*root)->left)); | |
} else { | |
(*root)->left = createNode(); | |
(*root)->left->n = data; | |
} | |
} else if (data > (*root)->n) { | |
if ((*root)->right != NULL) { | |
read_preorder(data,&((*root)->right)); | |
} else { | |
(*root)->right = createNode(); | |
(*root)->right->n = data; | |
} | |
} | |
} | |
void print_postorder(BTree *root) { | |
if (root->left != NULL) | |
print_postorder(root->left); | |
if (root->right != NULL) | |
print_postorder(root->right); | |
printf("%d\n",root->n); | |
} | |
void delete_postorder(BTree *root) { | |
if (root!= NULL) { | |
if (root->left != NULL) | |
delete_postorder(root->left); | |
if (root->right != NULL) | |
delete_postorder(root->right); | |
free(root); | |
} | |
} | |
int main() { | |
BTree *root = NULL; | |
int input; | |
while(!feof(stdin)) { | |
scanf("%d",&input); | |
read_preorder(input,&root); | |
} | |
print_postorder(root); | |
delete_postorder(root); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment