二叉树

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

int cnt;
char nodes[] = "6423####51##7##";
//二叉树结点
typedef struct BiTreeNode
{
    int val;
    struct BiTreeNode *lchild;
    struct BiTreeNode *rchild;

}BiTreeNode, *BiTree;

//按先序序列构造二叉树
BiTree createBiTree()
{
    BiTree root;
    if (nodes[cnt] == '\0')
    {
        return NULL;
    }
    if (nodes[cnt++] == '#')
    {
        root = NULL;
    }
    else
    {
        root = (BiTree)malloc(sizeof(BiTreeNode));
        root->val = nodes[cnt-1] - 48;
        root->lchild = createBiTree();//构造左子树
        root->rchild = createBiTree();//构造右子树
    }
    return root;
}

void visit(BiTree root)
{
    printf("%d ",root->val);
}

//前序遍历
void preOrder(BiTree root)
{
    if (root != NULL)
    {
        visit(root);//访问根结点
        preOrder(root->lchild);
        preOrder(root->rchild);
    }
}

//中序遍历
void inOrder(BiTree root)
{
    if (root != NULL)
    {
        inOrder(root->lchild);
        visit(root);
        inOrder(root->rchild);
    }
}

//后序遍历
void postOrder(BiTree root)
{
    if (root != NULL)
    {
        postOrder(root->lchild);
        postOrder(root->rchild);
        visit(root);
    }
}

int main()
{
    cnt = 0;
    BiTree root;
    root = createBiTree();
    printf("先序遍历二叉树: ");
    preOrder(root);
    printf("\n");
    printf("中序遍历二叉树: ");
    inOrder(root);
    printf("\n");
    printf("后序遍历二叉树: ");
    postOrder(root);
    printf("\n");
    return 0;
}


你可能感兴趣的:(二叉树)