二叉树的构建及后序遍历

#include"stdio.h"
#include"stdlib.h"
#include<iostream>
using namespace std;

typedef char ElemType;

typedef struct BiTNode{
    ElemType data;
    struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;

void CreatBiTree(BiTree &T){ //此处的T一定要加上取地址符,why?
    ElemType ch;
    cin >> ch;
    if(ch == '#')    
        T = NULL;//如果节点是叶节点,就不为其开辟存储空间
    else{
    //    if(!(T = (BiTNode *) malloc(sizeof(BiTNode))))
    //        exit(OVERFLOW); //节点内存分配失败就退出
        T = (BiTNode *) malloc(sizeof(BiTNode));
        T->data = ch;
        CreatBiTree(T->lchild);
        CreatBiTree(T->rchild);
    }
    return ;
}

void visit(BiTree node){
    //if(node->data != '#')
        cout << node->data;
}

void PostOrderTraverse(BiTree T){
    
    if(T){
    PostOrderTraverse(T->lchild);
    PostOrderTraverse(T->rchild);
    visit(T);
    }

    return ;
}

int main(){

    BiTree T;
    cout << "请以前序遍历的方式输入扩展二叉树:" <<endl;
    CreatBiTree(T);

    cout << "递归后序遍历输出为:" <<endl;
    PostOrderTraverse(T);

    cout << endl;
    return 1;
}

 

posted on 2017-12-06 10:14  帝孤  阅读(248)  评论(0编辑  收藏  举报

导航