码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的创建和遍历

时间:2016-12-17 19:58:26      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:div   sizeof   size   nbsp   bsp   scan   nod   com   str   

技术分享

以这颗树为例:#表示空节点
前序遍历(根->左->右)为:ABD##E##C#F##
中序遍历(左->根->右)为:#D#B#E#A#C#F#
后序遍历(左->右->根)为:##D##EB###FCA


 

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

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

}BiTNode,*BiTree;

void ForEachTree(BiTree T)
{
    if(T == NULL){
        return;
    }
//    printf(" %c ",T->data);前序遍历
    ForEachTree(T->lchild);
    printf(" %c ",T->data);//中序遍历
    ForEachTree(T->rchild);
//    printf(" %c ",T->data);后序遍历
}

void CreateBiTree(BiTree *T)
{
    TElemType ch;
    scanf("%c",&ch);
    if(# == ch){
        *T = NULL;
    }else{
        *T = (BiTree)malloc(sizeof(BiTNode));
    

        (*T)->data = ch;
        CreateBiTree(&(*T)->lchild);
    
        CreateBiTree(&(*T)->rchild);
    
    }
}
void main(){
    //前序创建树,中序输出树
    BiTree T;//根节点
    CreateBiTree(&T);

    ForEachTree(T);

}

技术分享

 

二叉树的创建和遍历

标签:div   sizeof   size   nbsp   bsp   scan   nod   com   str   

原文地址:http://www.cnblogs.com/wwzyy/p/6192803.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!