Tinh Do Cao Cua Nut Gia Tri Bang X Trong CNP
Written By 1 on Thứ Ba, 15 tháng 5, 2012 | 00:07
// Do Cao tai goc h la 0
//
#include "stdafx.h"
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef int element_type;
typedef struct node
{
element_type element;
struct node *left, *right;
} NODE;
NODE *root;
void khoi_tao_cay(NODE ** root)
{
*root = NULL;
}
void insert(NODE *tmp, NODE **root)
{
if (tmp->element < (*root)->element)
if ((*root)->left)
insert(tmp, &(*root)->left);
else
(*root)->left = tmp;
else
if ((*root)->right)
insert(tmp, &(*root)->right);
else
(*root)->right = tmp;
}
void insert_node(element_type e, NODE **root)
{
NODE *tmp;
tmp = (NODE *)malloc(sizeof(NODE));
tmp->element = e;
tmp->left = NULL;
tmp->right = NULL;
if (*root == NULL)
*root = tmp;
else
insert(tmp, root);
}
void nhap_cay(NODE **root)
{
element_type e;
printf("\n NHAP CAY NHI PHAN ! \n");
printf("\n Nhap -1 de ket thuc !\n ");
int i=1;
do {
printf("\n Nhap phan tu thu %d :",i);
scanf("%d", &e);
if (e != -1)
insert_node(e, root);
i++;
} while (e != -1);
}
char Search(NODE *root,int x)
{
NODE *temp = root;
while (temp != NULL ) {
if (temp -> element == x)
return 1;
else
{
if (temp -> element > x)
temp = temp -> left;
else
temp = temp -> right;
}
}
return 0;
}
int tinh_do_cao_gia_tri_x(NODE *root, int x)
{
if (root!=NULL)
{
if (root->element==x)
return 0;
if (root->element>x)
return 1+tinh_do_cao_gia_tri_x(root->left,x);
if (root->element<x)
return 1+tinh_do_cao_gia_tri_x(root->right,x);
}
}
void main()
{
khoi_tao_cay(&root);
nhap_cay(&root);
int x;
printf("\n Nhap gia tri can tim :");
scanf("%d",&x);
if(Search(root,x)==1)
printf("\n Do cao cua nut co gia tri bang %d la:%d ",x ,tinh_do_cao_gia_tri_x(root,x));
else
printf("\n Khong co nut gia tri bang %d trong cay!", x);
getch();
}
0 nhận xét:
Đăng nhận xét