构建二叉查找树的算法:
1、将第一个要创建的元素插入成为根节点。
2、将元素与结点值比较,如果元素值大于结点值,将此元素值送往结点的右子节点,如果右子节点并不是空的,需要重复比较,否则创建结点将元素值插入。
1、将第一个要创建的元素插入成为根节点。
2、将元素与结点值比较,如果元素值大于结点值,将此元素值送往结点的右子节点,如果右子节点并不是空的,需要重复比较,否则创建结点将元素值插入。
3、如果元素值小于结点值,将此元素送往结点的左子结点,如果左子节点不是空的,需要重复比较,否则创建结点将元素值插入。
算法实现代码:
/*btree.h*/
#ifndef BTREE_H
#define BTREE_H
typedef struct treenode;
typedef treenode *btree;
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
btree insertnode(btree root, int value);
btree createbtreee(int *data, int len);
void printbtree(tree root);
#endif
/*btree.c*/
#include<stdio.h>
#include "btree.h"
btree insertnode(btree root, int value)
{
btree newnode;
btree current;
btree back;
newnode = (btee)malloc(sizeof(treenode));
newnode->data = value;
newnode->left = NULL;
newnode->right = NULL;
if (root == NULL)
{
return newnode;
}
else
{
current = root;
while (current != NULL)
{
back = current;
if (current->data > value)
current = current->left;
else
current = current->right;
}
if (back->data > value)
{
back->left = newnode;
}
else
{
back->right = newnode;
}
}
return root;
}
btree createbtree(int *data, int len)
{
btree root;
int i;
for (i = 0; i < len; i++)
root = insertnode(root, data[i]);
return root;
}
void printbtree(btree root)
{
btree ptr;
ptr = root->left;
printf ("输出左子树:\n");
while (ptr != NULL)
{
printf("%2d\n", ptr->data);
ptr = ptr->left;
}
ptr = root->right;
printf("输出右子树:\n");
while (ptr != NULL)
{
printf("%2d\n", ptr->data);
ptr = ptr->right;
}
}
/*main.c*/
#include<stdio.h>
#include "btree.h"
void main(void)
{
btree root = NULL;
int data[10] = { 5, 6, 4, 8, 2, 3, 7, 1, 9 };
root = createbtree(root, 9);
printf("二叉树结点:\n");
printbtree(root);
}
/*Makfile*/
main: main.o btree.o
gcc -o main.o btree.o
main.o: main.c btree.h
gcc -c main.c
btree.o: btree.c btree.h
gcc -c btree.c