概念,操作(建立,插入,删除,遍历)前序遍历,中序遍历,后序遍历
分类:满二叉树,完全二叉树,最优二叉树(哈弗曼树)
二叉查找树,是指左孩子小于根节点,右节点大于根节点.它的插入
删除很麻烦
平衡二叉查找树AVL,左右节点的差的绝对值小于等于1
B树见下节
实现了二叉查找树的建立,插入,遍历。没有删除,都是基本的。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
struct Node
{
long item;
int count;
Node* pLeft;
Node* pRight;
};
Node* createTree(long value);
Node* addNode(long value, Node*);
void printTree(Node*); //递归升序打印出来
void freeTree(Node*); //释放结点
void main()
{
long newvalue = 0;
Node* pRoot = NULL;
int answer = 1;
do
{
printf("enter the node value:");
scanf("%ld",&newvalue);
// printf("输入的数据为:%ld\n",newvalue);
if (pRoot==NULL)
pRoot = createTree(newvalue);
else
addNode(newvalue,pRoot);
printf("do you want to enter another (1 or 0)?");
scanf("%d",&answer);
} while (tolower(answer) == 1);
printf("the values in ascending sequences are:");
printTree(pRoot);
freeTree(pRoot);
}
Node* createTree(long val)
{
Node* pNode = (Node*)malloc(sizeof(Node) );
pNode->item = val;
pNode->count = 1;
pNode->pLeft = pNode->pRight = NULL;
printf("插入的数据为:%ld\n",pNode->item);
return pNode;
}
Node* addNode(long val,Node* pNode)
{
if (pNode == NULL)
{
return createTree(val);
}
if (val== pNode ->item) // == 写成 = 号就大错了啊。仔细啊
{
++pNode->count;
return pNode;
}
if (val<pNode->item)
{
if (pNode->pLeft == NULL)
{
pNode->pLeft=createTree(val);
return pNode->pLeft;
}
else
return addNode(val,pNode->pLeft);
}
if (val>pNode->item)
{
if (pNode->pRight ==NULL)
{
pNode->pRight = createTree(val);
return pNode->pRight;
}
else
return addNode(val,pNode->pRight);
}
}
void printTree( Node* pNode) //根左右 前序遍历 递归法
{
for(int i=0; i<pNode->count;i++)
{
printf("\n%ld\n",pNode->item);
}
if (pNode->pLeft!=NULL)
{
printTree(pNode->pLeft);
}
if (pNode->pRight!=NULL)
{
printTree(pNode->pRight);
}
}
void freeTree( Node* pNode)
{
if (pNode==NULL)
{
return;
}
if (pNode->pLeft!=NULL)
{
freeTree(pNode->pLeft);
}
if (pNode->pRight!=NULL)
{
freeTree(pNode->pRight);
}
free(pNode);
}
结果