Code duyệt cây nhị phân tìm kiếm – C++

#include <stdio.h>
#include <conio.h>
#include <alloc.h>

typedef int element_type;
typedef struct node {
element_type element;
struct node *left, *right;
} NODE;
<!--more-->
NODE *root;

void khoi_tao_cay(NODE ** root)
{
*root = NULL;
}

void insert(NODE *tmp, NODE **root)
{

if (tmp-&gt;element &lt; (*root)-&gt;element)
if ((*root)-&gt;left)
insert(tmp, &amp;(*root)-&gt;left);
else
(*root)-&gt;left = tmp;
else
if ((*root)-&gt;right)
insert(tmp, &amp;(*root)-&gt;right);
else
(*root)-&gt;right = tmp;
}

void insert_node(element_type e, NODE **root)
{
NODE *tmp;

tmp = (NODE *)malloc(sizeof(NODE));
tmp-&gt;element = e;
tmp-&gt;left = NULL;
tmp-&gt;right = NULL;
if (*root == NULL)
*root = tmp;
else
insert(tmp, root);
}

void nhap_cay(NODE **root)
{
element_type e;
do {
printf("\nNhap element (-1 de ket thuc) : ");
scanf("%d", &amp;e);
if (e != -1)
insert_node(e, root);
} while (e != -1);
}

void NLR(NODE *root)
{
if (root != NULL)
{
printf("%d ", root-&gt;element);
NLR(root-&gt;left);
NLR(root-&gt;right);
}
}

void NRL(NODE *root)
{
if (root != NULL)
{
printf("%d ", root-&gt;element);
NRL(root-&gt;right);
NRL(root-&gt;left);
}
}

void LNR(NODE *root)
{
if (root != NULL)
{
LNR(root-&gt;left);
printf("%d ", root-&gt;element);
LNR(root-&gt;right);
}
}

void LRN(NODE *root)
{
if (root != NULL)
{
LRN(root-&gt;left);
LRN(root-&gt;right);
printf("%d ", root-&gt;element);
}
}

void RNL(NODE *root)
{
if (root != NULL)
{
RNL(root-&gt;right);
printf("%d ", root-&gt;element);
RNL(root-&gt;left);
}
}

void RLN(NODE *root)
{
if (root != NULL)
{
RLN(root-&gt;right);
RLN(root-&gt;left);
printf("%d ", root-&gt;element);
}
}

void main()
{
khoi_tao_cay(&amp;root);
nhap_cay(&amp;root);
printf("\nDuyet cay NLR : ");
NLR(root);
printf("\nDuyet cay NRL : ");
NRL(root);
printf("\nDuyet cay LNR : ");
LNR(root);
printf("\nDuyet cay LRN : ");
LRN(root);
printf("\nDuyet cay RNL : ");
RNL(root);
printf("\nDuyet cay RLN : ");
RLN(root);
getch();
}
Advertisements

4 thoughts on “Code duyệt cây nhị phân tìm kiếm – C++

  1. Nice post. I learn something new and challenging on sites I stumbleupon every
    day. It’s always helpful to read through articles from other writers and use a little
    something from their sites.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s