Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1681642
  • 博文数量: 1493
  • 博客积分: 38
  • 博客等级: 民兵
  • 技术积分: 5834
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-19 17:28
文章分类

全部博文(1493)

文章存档

2016年(11)

2015年(38)

2014年(137)

2013年(253)

2012年(1054)

2011年(1)

分类:

2012-07-04 08:50:26

原文地址:二叉树遍历(纯C) 作者:教鱼斿泳

中序遍历 左根右
先序遍历 根左右
后序遍历 左右根
顺序是以根的位置来命名的,中,根在中间,先,根在前面。
 
#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");
}
阅读(223) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~