二叉排序树的建立思想是比较简单的,即首先建立一个根结点,然后插入值比根节点值小,就成为根节点的左孩子,比它值大则成为根节点的右孩子。
需要注意的就是我们应该对它的左右孩子是否为空进行判断,如果为空,则要建立新的结点;如果不为空,则直接赋值过去即可。
#include<stdio.h>
#include<stdlib.h>
#define size 7
typedef struct BNode
{
int key;
struct BNode* rightchild;
struct BNode* leftchild;
}*BNPtr;
int data[size] = { 45, 24, 53, 45, 12, 46, 90 };
BNPtr BST()
{
int i;
BNPtr root;
BNPtr temPtr;
BNPtr tempNewPtr;
root = (BNPtr)malloc(sizeof(struct BNode));
root->leftchild = NULL;
root->rightchild = NULL;
root->key = data[0];
for (i = 1; i<size; i++)
{
temPtr = root;
while (temPtr != NULL)
{
if (data[i] == temPtr->key)
{
printf("%d exist\n", data[i]);
break;
}
else if (data[i]<temPtr->key)
{
if (temPtr->leftchild == NULL)
{
tempNewPtr = (BNPtr)malloc(sizeof(struct BNode));
tempNewPtr->leftchild = NULL;
tempNewPtr->rightchild = NULL;
tempNewPtr->key = data[i];
temPtr->leftchild = tempNewPtr;
printf("%d is the %d 's leftchild\r\n", data[i], temPtr->key);
break;
}
else
{
temPtr = temPtr->leftchild;
}
}
else
{
if (temPtr->rightchild == NULL)
{
tempNewPtr = (BNPtr)malloc(sizeof(struct BNode));
tempNewPtr->leftchild = NULL;
tempNewPtr->rightchild = NULL;
tempNewPtr->key = data[i];
temPtr->rightchild = tempNewPtr;
printf("%d is the %d 's rightchild\r\n", data[i], temPtr->key);
break;
}
else
{
temPtr = temPtr->rightchild;
}
}
}
}
return root;
}
void inorder(BNPtr temPtr)
{
if (temPtr->leftchild != NULL)
{
inorder(temPtr->leftchild);
}
printf("%d\n", temPtr->key);
if (temPtr->rightchild != NULL)
{
inorder(temPtr->rightchild);
}
}
int main()
{
BNPtr temPtr;
temPtr = BST();
printf("中序遍历:\n");
inorder(temPtr);
return 0;
}