中序遍历 左根右
先序遍历 根左右
后序遍历 左右根
顺序是以根的位置来命名的,中,根在中间,先,根在前面。
#include
#include
struct tree
{
int data;
struct tree* lchild,*rchild;
};
struct tree* create(int *nodelist, int position)
{
struct tree* newnode;
if(nodelist[position]==0||position>15)
return NULL;
else
{
newnode = (struct tree*) malloc(sizeof(struct tree));
newnode->data=nodelist[position];
newnode->lchild=create(nodelist,2*position);
newnode->rchild=create(nodelist,2*position+1);
return newnode;
}
}
void preorder(struct tree *p)
{
if(p!=NULL)
{
printf("%d\n",p->data);
preorder(p->lchild);
preorder(p->rchild);
}
}
void inorder(struct tree *p)
{
if(p!=NULL)
{
inorder(p->lchild);
printf("%d\n",p->data);
inorder(p->rchild);
}
}
void fallorder(struct tree *p)
{
if(p!=NULL)
{
fallorder(p->lchild);
fallorder(p->rchild);
printf("%d\n",p->data);
}
}
int main()
{
struct tree* root = NULL;
int nodelist[16] = {0,5,2,9,1,4,7,0,0,0,3,0,6,8,0,0};
root = create(nodelist, 1);
printf("create successful\n");
preorder(root);
printf("finish preorder\n");
inorder(root);
printf("finish inorder\n");
fallorder(root);
printf("finish fallorder\n");
}
阅读(366) | 评论(0) | 转发(0) |