Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- struct treenode {
- struct treenode *left;
- struct treenode *right;
- int data;
- };
- typedef struct treenode TREENODE;
- typedef TREENODE *TREE;
- void insert_node(TREE *tp, int value);
- void preorder_print(TREE t);
- int is_empty_tree ( TREE t );
- int root_value(TREE t);
- int is_perfect_tree(TREE t);
- int size(TREE t);
- int is_perfect_level(TREE t);
- int main(){
- TREE t = NULL;
- int i = 0, tmp;
- do{
- printf("N%02d: ", i + 1);
- scanf(" %d", &tmp);
- if(tmp==0){
- break;
- }
- insert_node(&t,tmp);
- i++;
- }while(tmp > 0);
- preorder_print(t);
- printf(" = %s\n", is_perfect_tree(t) ? "Yes" : "No");
- return 0;
- }
- void insert_node(TREE *tp, int value) {
- if (*tp == NULL) {
- // printf("tp == null\n");
- *tp = malloc(sizeof(TREENODE));
- (*tp)->data = value;
- (*tp)->left = NULL;
- (*tp)->right = NULL;
- }else if (value < (*tp)->data ){
- printf(" <<<\n");
- insert_node(&((*tp)->left), value);
- }else if (value > (*tp)->data ){
- printf(" >>>\n");
- insert_node(&((*tp)->right), value);
- }else{
- printf("duplicate node\n");
- }
- }
- int is_empty_tree ( TREE t ){
- if (t == NULL) {
- // printf("in empty null\n");
- return 1;
- }else{
- // printf("NO in empty null\n");
- return 0;
- }
- }
- int root_value(TREE t){
- if (!is_empty_tree){
- fprintf(stderr, "Tree is empty \n");
- return -1;
- }else{
- return t->data;
- }
- }
- TREE ls_tree(TREE t){
- // printf("left\n");
- return t->left;
- }
- TREE rs_tree(TREE t){
- // printf("right\n");
- return t->right;
- }
- void preorder_print(TREE t){
- if (!is_empty_tree(t)) {
- printf("%d\n", root_value(t));
- preorder_print(ls_tree(t));
- preorder_print(rs_tree(t));
- }
- }
- int perfect_level(TREE t){
- if(t==NULL)
- return 1;
- else if(t->left==NULL && t->right==NULL)
- return 1;
- else if(t->left==NULL || t->right==NULL)
- return 0;
- else
- return is_perfect_tree(t->left)&&is_perfect_tree(t->right);
- }
- int is_perfect_tree(TREE t){
- if(perfect_level(t)==1 && size(t->left)==size(t->right))
- return 1;
- else
- return 0;
- }
- int size(TREE t){
- if(t==NULL)
- return 0;
- else
- return (1 + size(t->left) + size(t->right));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement