In Nut Thu K Cua CNPTK
Written By 1 on Thứ Hai, 14 tháng 5, 2012 | 07:37
#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);
}
void tim_xuat_nguoc(NODE *root, int x)
{
if(!root)
printf("\n Cay rong !");
else
if(root->element==x)
printf(" %d",root->element);
else
if(root->element>x)
{
tim_xuat_nguoc(root->left,x);
printf(" %d", root->element);
}
else
{
tim_xuat_nguoc(root->right,x);
printf(" %d", root->element);
}
}
void in_nut_thu_k(NODE *root, int k)
{
if(!root)
return;
if(k==0)
{
printf(" %d", root->element);
}
in_nut_thu_k(root->left,k-1);
in_nut_thu_k(root->right, k-1);
}
void in_nut_thu_k(NODE *root, int k);
void duyet_theo_mut(NODE *root, int x)
{
for(int k=x;k>=1;k--)
in_nut_thu_k(root,k);
}
void main()
{
khoi_tao_cay(&root);
nhap_cay(&root);
// xuat cac phan tu , tu phan tu =x ve goc
int x;
printf("\n Nhap gia tri xuat nguoc :");
scanf("%d",&x);
tim_xuat_nguoc(root,x);
int h; // do cao
printf("\n Nhap mut can in:");
scanf("%d",&h);
printf("\n Gia tri cac nut o do cao %d:", h);
in_nut_thu_k(root,h);
// xuat cac phan tu tu do cao h ve goc
printf("\n Xuat cac phan tu tu do cao %d ve goc :",h);
duyet_theo_mut(root, h);
getch();
}
0 nhận xét:
Đăng nhận xét