建二叉树的模板(指针,链表型)

首先是结构体的定义

typedef struct node  
{  
    struct node *leftChild;  
    struct node *rightChild;  
    char data;  
}BiTreeNode, *BiTree; 

二叉树的四种遍历(先序,中序,后序,层次)

1.先序

void printTree3(BiTree &T){//xian
    if(T==NULL){
        return ;
    }else{  
	printf("%c",T->data);
    printTree2(T->leftChild);
    printTree2(T->rightChild);
    
    }
}

2.中序

void printTree1(BiTree &T){//zhong
    if(T==NULL){
        return;
    }else{
    printTree1(T->leftChild);
    printf("%c",T->data);
    printTree1(T->rightChild);
    }   
}

3.后序

void printTree2(BiTree &T){//hou
    if(T==NULL){
        return ;
    }else{  
    printTree2(T->leftChild);
    printTree2(T->rightChild);
    printf("%c",T->data);
    }
}

4.层次遍历

//第一种写法
void PrintAtLevel(Tree T) {
	queue myqueue;
	myqueue.push(T);
	while (!myqueue.empty()) {
		Tree tmp = myqueue.front();
		if (tmp->lchild != NULL)
			myqueue.push(tmp->lchild);
		if (tmp->rchild != NULL)
			myqueue.push(tmp->rchild);
		cout << tmp->value << " ";
		myqueue.pop();
	}
}

//第二种写法
void LevelOrderTraversal(Ptree BT)
{
	Queue Q;
	Ptree T;
	if(!BT) return;
	Q=CreateQueue();
	T=BT;
	InsertQ(T,Q);
	while(!IsEmpty(Q)){
		T=DeleteQ(Q);
		printf("%c",T->data);
		if(T->lchild) InsertQ(T->lchild,Q);
		if(T->rchild) InsertQ(T->rchild,Q);
	}
};
//第三种
void LevleOrder(BiTree T)
{ /*层次遍历二叉树T,从第一层开始,每层从左到右*/
  BiTree Queue[MAX],b;/*用一维数组表示队列,front和rear分别表示队首和队尾指针*/
  int front,rear;
  front=rear=0;
  if(T) /*若树非空*/
  {
     Queue[rear++]=T;           /*根结点入队列*/
     while (front!=rear)
     {                          /*当队列非空*/
       b=Queue[front++];        /*队首元素出队列,并访问这个结点*/
       printf("%2c",b->data);
       if(b->lchild!=NULL) Queue[rear++]=b->lchild; /*左子树非空,则入队列*/
       if(b->rchild!=NULL) Queue[rear++]=b->rchild; /*右子树非空,则入队列*/
     }
  }
}/*LevelOrder*/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值