二叉树的先中后序三种遍历,和先序的建立,代码详解!!

来源:互联网 发布:日语教学软件 编辑:程序博客网 时间:2024/06/08 04:04

#include<stdio.h>
#include<stdlib.h>
/***
 二叉链表建立二叉树的时候输入为0的时候为空节点
(而空节点下面是不会再有节点的)(输入的是字符,各个字符代表节点)
  输入结束时保证构造的二叉树的叶子节点有两个空的子节点。构造的图如下所示:
  列如输入为:ABC00DE0G00F000


 怎么才能输入结束?因为是递归输入,而最终递归结束的时候输入就结束。

**/
</pre><img src="http://img.blog.csdn.net/20141224202707282?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveHVxaW5nZ2FuZ3Nscw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" style="font-family:Simsun; font-size:14px" /><p></p><p></p><pre code_snippet_id="561477" snippet_file_name="blog_20141224_2_9877573" name="code" class="cpp"><span style="font-size:18px;"><span style="font-size:18px;">typedef struct BiNode{    char nd;    struct BiNode *leftChild;    struct BiNode *rightChild;}BiNode,*BiRoot;BiRoot biRoot;// 二叉树的根节点指针char ch;/** 此处BiRoot 是指针类型    所以下面申请内存的时候 是:sizeof(BiNode) 而不是sizeof(BiRoot)    自行查看sizeof()的作用!**/// 初始化一个带根节点的树bool initBiTree(){    biRoot = (BiRoot)malloc(sizeof(BiNode));    biRoot->leftChild=NULL;    biRoot->rightChild=NULL;    biRoot->nd=' ';}/**注意下面函数中形参是指针类型的引用若形参只是指针类型,(形参是一个新变量)接收实参传的地址。请看图理解一下:**/// 先序建立二叉树(0代表虚空节点)void preCreateBiTree(BiRoot &T){    scanf("%c",&ch);    if(ch=='0') T=NULL;    else{        T = (BiRoot)malloc(sizeof(BiNode));        T->nd = ch;        preCreateBiTree(T->leftChild);        preCreateBiTree(T->rightChild);    }    return ;}/**先中后 3种遍历二叉树的区别在于输出语句的位置。原因:递归是自上而下的递推,自下而上的解决问题。先序:根,左节点,右节点 : 先输出根,再输出左子树的根,再输出左子树的左孩子为根的子树的根。。。。中序:左节点,根,右节点后序:左节点,右节点,根**/// 先序输出二叉树void prePrintBiTree(BiRoot T){    if(T){        printf("%c ",T->nd);        prePrintBiTree(T->leftChild);        prePrintBiTree(T->rightChild);    }    return ;}//中序输出二叉树void inPrintBiTree(BiRoot T){    if(T){        inPrintBiTree(T->leftChild);        printf("%c ",T->nd);        inPrintBiTree(T->rightChild);    }    return ;}// 后序遍历二叉树void postPrintBiTree(BiRoot T){    if(T){        postPrintBiTree(T->leftChild);        postPrintBiTree(T->rightChild);        printf("%c ",T->nd);    }    return ;}int main(){    printf("先序建立二叉树:\n");    preCreateBiTree(biRoot);    printf("先序遍历二叉树:");    prePrintBiTree(biRoot);    printf("\n");    printf("中序遍历二叉树:");    inPrintBiTree(biRoot);    printf("\n");    printf("后序遍历二叉树:");    postPrintBiTree(biRoot);}</span></span>


0 0
原创粉丝点击