先序创建二叉树

来源:互联网 发布:淘宝图片视频在线制作 编辑:程序博客网 时间:2024/05/21 13:54

已知二叉树如下图,空节点用*表示,输入时则输入0代替。
input:1 2 0 4 0 0 3 0 5 0 0

         1     2      3   *  4   *   5    *   *   *   *

这里写图片描述

#include<stdio.h>#include<stdlib.h>typedef struct BTNode{    struct BTNode *lchild,*rchild;    int data;}BTNode,*btnode;void createBtree(btnode &T){    int t;    scanf("%d",&t);    if(t==0)        T=NULL;    else    {        T=(btnode)malloc(sizeof(BTNode));        T->data=t;        createBtree(T->lchild);        createBtree(T->rchild);    }}void preOrder(btnode T){    if(T)    {        printf("%d ",T->data);        preOrder(T->lchild);        preOrder(T->rchild);    }}void inOrder(btnode T){    if(T)    {        inOrder(T->lchild);        printf("%d ",T->data);        inOrder(T->rchild);    }}void postOrder(btnode T){    if(T)    {        postOrder(T->lchild);        postOrder(T->rchild);        printf("%d ",T->data);    }}int main(){    btnode T=NULL;    createBtree(T);    printf("output preorder: ");    preOrder(T);    printf("\n");    printf("output inorder: ");    inOrder(T);    printf("\n");    printf("output postorder: ");    postOrder(T);    printf("\n");    return 0;}
0 0
原创粉丝点击