---
title: "二叉排序树"
author: "vergilwang"
date: "2011-10-31T15:46:00Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2014-02-15T16:27:46Z"
id: 2011433
url: "https://vergilwang.iteye.com/blog/2011433"
---

#include &lt;stdio.h&gt;  
#include &lt;stdlib.h&gt;  
#include &lt;string.h&gt;  
#include &lt;time.h&gt;  
struct tree\_node  
{  
int data;  
struct tree\_node \*left\_ptr;  
struct tree\_node \*right\_ptr;  
};  
void insert\_node(struct tree\_node \*\*, int);  
void pre\_order(struct tree\_node \*);  
void in\_order(struct tree\_node\*);  
void post\_order(struct tree\_node\*);

int main()  
{  
int i, item;  
struct tree\_node* root\_ptr = NULL;

srand(time(NULL));  
for(i=0; i&lt;10; i++)  
{  
item = rand()%15;  
printf("%3d", item);  
insert\_node(&root\_ptr, item);  
}  
puts("pre\_order");  
pre\_order(root\_ptr);  
puts("in\_order");  
in\_order(root\_ptr);  
puts("post\_order");  
post\_order(root\_ptr);  
return EXIT\_SUCCESS;  
}

void insert\_node(struct tree\_node \*\*tree\_ptr, int value)  
{  
if (\*tree\_ptr == NULL)  
{  
\*tree\_ptr = malloc(sizeof(struct tree\_node));

if (\*tree\_ptr != NULL)//malloc successfully  
{  
(\*tree\_ptr)-&gt;data = value;  
(\*tree\_ptr)-&gt;left\_ptr = NULL;  
(\*tree\_ptr)-&gt;right\_ptr = NULL;  
}  
else  
{  
printf("%d not inserted. No memory available\\n", value);  
}  
}  
else//the tree is not null  
{  
if (value &lt; (\*tree\_ptr)-&gt;data)  
{  
insert\_node(&((\*tree\_ptr)-&gt;left\_ptr), value);  
}  
else if (value &gt; (\*tree\_ptr)-&gt;data)  
{  
insert\_node(&((\*tree\_ptr)-&gt;right\_ptr), value);  
}  
else//the equal value is not inserted  
{  
puts("dup");  
}

}  
}

void pre\_order(struct tree\_node \*ptr)  
{  
if (ptr != NULL)  
{  
printf("%3d", ptr-&gt;data);  
pre\_order(ptr-&gt;left\_ptr);  
pre\_order(ptr-&gt;right\_ptr);  
}  
}

void in\_order(struct tree\_node \*ptr)  
{  
if (ptr != NULL)  
{  
in\_order(ptr-&gt;left\_ptr);  
printf("%3d", ptr-&gt;data);  
in\_order(ptr-&gt;right\_ptr);  
}  
}

void post\_order(struct tree\_node \*ptr)  
{  
if (ptr != NULL)  
{  
post\_order(ptr-&gt;left\_ptr);  
post\_order(ptr-&gt;right\_ptr);  
printf("%3d", ptr-&gt;data);  
}  
}