posts - 63, comments - 37, trackbacks - 0, articles - 0
  IT博客 :: 首页 :: 新随笔 :: 联系 ::  :: 管理

二叉树的遍历

Posted on 2006-06-08 21:57 Enjoy Life 阅读(653) 评论(0)  编辑 收藏 引用 所属分类: DS study

树的遍历:实际访问树中各个节点时,需要路过节点三次,如果如果第一次访问该节点就对其实施Visit函数的话,称为先序遍历,第二访问时实施Visit函数,则为中序遍历,最后访问时实施则为后序遍历。



#include <stdio.h>
#include <stdlib.h>

typedef int    TElemType;
//typedef 1 OK;
//typedef 0 ERROR;

#define OK 1;
#define ERROR 0;

typedef struct BiTNode {
 TElemType data;
 struct BiTNode  *lchild, *rchild;
}BiTNode;

int PrintElem(TElemType e){
 printf("Node Elem is %d", e);
 return OK; 
}


int PreOderTraverse(BiTNode *tree, int(* PrintElem)(TElemType e)){
 if(tree){
  if(PrintElem(tree->data))
   if(PreOderTraverse(tree->lchild, PrintElem))
    if(PreOderTraverse(tree->rchild,PrintElem))
     return OK;
  return ERROR;
       
 }
 else
  return OK;
}


//Create New Tree;

int CreateBiTree(BiTNode *tree){
 BiTNode *T;
 printf("please input int data to create bitree, enter 0 for finishing\n");
 TElemType i;
 scanf("%d",&i);
 if (i == 0){
  T = NULL;
  printf("Tree is NULL \n ");
  return ERROR;
 }
 else {
  if(!(T = (BiTNode *)malloc(sizeof(BiTNode)))){
   printf("OverFlow\n");
   return ERROR;
  }
  T->data = i;
  CreateBiTree(T->lchild);
  CreateBiTree(T->rchild);
  
 }//else end
}


void main()

 BiTNode *Tree;
 printf("input data to create a new BiTree \n");
 CreateBiTree(Tree);
 PreOderTraverse(Tree,PrintElem);
 return ;
}


 

只有注册用户登录后才能发表评论。