您的位置:首页 > 其它

二叉树创建及遍历(递归遍历)

2010-03-20 22:02 330 查看
#include <stdio.h>
#include <stdlib.h>

/*--------------------------------------------
//二叉树节点定义,
data:数据
left:左指针
right:右指针
--------------------------------------------*/
typedef struct binNode
{
int data;
binNode* left;
binNode* right;
}*bintree, bintreeNode;

binNode* createtree(binNode*);
void destroytree(binNode*);
binNode* preordertravel(binNode*,int);
void inordertravel(binNode*);
void postordertravel(binNode*);
void leveltravel(binNode* p);
bintree find(binNode*, int item);

void main()
{
bintree root;
root = 0;
root = createtree(root);
printf("前序:/n");
bintree temp = preordertravel(root, 8);

if (temp == 0)
{
printf("no item/n");
}
else
printf("/n%d/n", temp->data);

printf("/n中序:/n");
inordertravel(root);
printf("/n后序:/n");
postordertravel(root);
printf("/n后序:/n");
leveltravel(root);

destroytree(root);
}

//创建二叉树
binNode* createtree(bintree p)
{
int c;
bintree temp;
bintree di;
bintree t;
do
{
scanf("%d", &c);

temp = (bintree)malloc(sizeof(bintreeNode));
if (temp == 0)
{
printf("memory error");
exit(1);
}
temp->left = 0;
temp->right = 0;
temp->data = c;

if (p == 0)
{
p = temp;
}
else
{
di = p;
while (di != 0)
{
t = di;
if (c < di->data)
{
di = di->left;
}
else
{
di = di->right;
}

}

if (c < t->data)
{
t->left = temp;
}
else
{
t->right = temp;
}
}
} while(c != 0);

return p;
}

//删除二叉树
void destroytree(binNode* root)
{
bintree temp =root;
bintree t;
if (temp != 0)
{

destroytree(temp->left);
destroytree(temp->right);

free(temp);
temp = NULL;

}
}

//查找item,返回节点值为item的指针
bintree find(binNode*p, int item)
{
bintree temp = p;
if (p == NULL)
{
printf("empty tree/n");
exit(0);
}
while ( temp != NULL )
{
if ( temp->data == item)
{
return temp;
break;
}

}
return NULL;
}

//前序遍历(中、左、右),在前序遍历过程中查找某个值是否存在
bintree preordertravel(bintree p, int item)
{
bintree temp = 0;
if (p != 0)
{
if (p->data == item)
{
temp = p;
}
printf("%d ",p->data);
preordertravel(p->left, item);
preordertravel(p->right,item);
}
return temp;
}

//中序遍历(左、中、右)
void inordertravel(bintree p)
{
if (p != 0)
{
inordertravel(p->left);
printf("%d ", p->data);
inordertravel(p->right);
}

}

//后续遍历(左、右、中)
void postordertravel(bintree p)
{
if (p != 0)
{
postordertravel(p->left);
postordertravel(p->right);
printf("%d ", p->data);
}

}

//层序遍历
void leveltravel(binNode* p)
{
binNode* t[20];
int rear = 0;
int front = 0;
if ( p )
{
++rear;
t[rear] = p;
}

while ( front != rear )
{
front++;
printf("%d ",t[front]->data);
if (t[front]->left != NULL)
{
rear++;
t[rear] = t[front]->left;
}
if (t[front]->right != NULL)
{
rear++;
t[rear] = t[front]->right;
}
}
}

binNode* initree(binNode* root, int a[], int n)
{
int i;
for ( i = 0; i < n; i++)
{
binNode* temp;
temp = (binNode*)malloc(sizeof(binNode));
if (temp == NULL)
{
return NULL;
}
temp->data = a[i];
temp->left = NULL;
temp->right = NULL;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: