其他分享
首页 > 其他分享> > 根据先序遍历结果建立二叉树

根据先序遍历结果建立二叉树

作者:互联网

(防止自己那天又忘了---重复学习)

参考:https://blog.csdn.net/xfxf996/article/details/80869064

C++实现:

#include <stdio.h>
#include <stdlib.h>
typedef struct TNode
{
    char ch;
    struct TNode *left,*right;
}*BTree,TNode;

void createTree(BTree &T)//C++的引用
{
    char temp;
    scanf("%c",&temp);
    if(temp=='#')
    {
        T=NULL;
    }
    else
    {
        T=(TNode *)malloc(sizeof(TNode));
        T->ch=temp;
        createTree(T->left);
        createTree(T->right);
        return;
    }
}

void xian(BTree T)//先序
{
    if(T)
    {
        printf("%c ",T->ch);
        xian(T->left);
        xian(T->right);
    }
}
void zhong(BTree T)//中序
{
    if(T)
    {
        zhong(T->left);
        printf("%c ",T->ch);
        zhong(T->right);
    }
}
void hou(BTree T)//后序
{
    if(T)
    {
        hou(T->left);
        hou(T->right);
        printf("%c ",T->ch);
    }
}

int main()
{
    BTree T;
    T=NULL;
    createTree(T);
    zhong(T);
    return 0;
}

C实现:

#include <stdio.h>
#include <stdlib.h>
typedef struct TNode
{
    char ch;
    struct TNode *left,*right;
}*BTree,TNode;

BTree createTree(BTree T)//返回指针,就可以不用引用,C里面没有引用
{
    char temp;
    scanf("%c",&temp);
    if(temp=='#')
    {
        T=NULL;
        return T;
    }
    else
    {
        T=(TNode *)malloc(sizeof(TNode));
        T->ch=temp;
        T->left=createTree(T->left);
        T->right=createTree(T->right);
        return T;
    }
}

void inorder(BTree T)
{
    if(T)
    {
        inorder(T->left);
        printf("%c ",T->ch);
        inorder(T->right);
    }
}

int main()
{
    BTree T;
    T=NULL;//初始化
    T=createTree(T);
    inorder(T);
    return 0;
}

 

标签:遍历,createTree,ch,TNode,right,二叉树,left,BTree,先序
来源: https://blog.csdn.net/qq_41462385/article/details/88285957