二叉树遍历

按照网上代码写了一个二叉树创建和遍历

// datastructure.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include "Search.hpp"

typedef struct _BiNode
{
    int          data;
    _BiNode     *left;
    _BiNode     *right;
}BiNode, *PBiNode;

typedef void (*VisitType)(int);

static char s_pEleSet[]="123456789abc";
static char s_pOrder[]="vvvveeveeveevvveevveeveee";
static int  s_iCurEle = 0;
static int  s_iCurOrder=0;

void PrintNode(int value)
{
    printf("current node = %c\n", value);
}

int CreateBinaryTree(PBiNode* pRoot, VisitType func)
{
    if(s_pOrder[s_iCurOrder++] == 'e')
        *pRoot = NULL;
    else
    {
        *pRoot=(PBiNode)malloc(sizeof(BiNode));
        if(NULL != *pRoot )
        {
            (*pRoot)->data = s_pEleSet[s_iCurEle++];
            printf("cur node %c 's leftchild\n",(*pRoot)->data);
            CreateBinaryTree(&(*pRoot)->left,func);
            printf("cur node %c 's rightchild\n",(*pRoot)->data);
            CreateBinaryTree(&(*pRoot)->right,func);
        }
    }
    return 0;
}




//pre-order binaryTree traverse
int PreOrderBinaryTreeTraverse(PBiNode pRoot, VisitType func)
{
    if(NULL == pRoot)
        return 0;
    else
    {
        func(pRoot->data);
        PreOrderBinaryTreeTraverse(pRoot->left, func);
        PreOrderBinaryTreeTraverse(pRoot->right, func);
    }

    return 0;   
}



//In-order binaryTree traverse
int InOrderBinaryTreeTraverse(PBiNode pRoot, VisitType func)
{
    if(NULL == pRoot)
        return 0;
    else
    {
        InOrderBinaryTreeTraverse(pRoot->left, func);
        func(pRoot->data);
        InOrderBinaryTreeTraverse(pRoot->right, func);
    }

    return 0;   
}


//post-order binaryTree traverse
int PostOrderBinaryTreeTraverse(PBiNode pRoot, VisitType func)
{
    if(NULL == pRoot)
        return 0;
    else
    {
        PostOrderBinaryTreeTraverse(pRoot->left, func);
        PostOrderBinaryTreeTraverse(pRoot->right, func);
        func(pRoot->data);
    }
    return 0;       
}



int _tmain(int argc, _TCHAR* argv[])
{
    PBiNode ptree=NULL;
    CreateBinaryTree(&ptree, PrintNode);
    printf("Pre Order:\n"); 
    PreOrderBinaryTreeTraverse(ptree,PrintNode);
    printf("In Order:\n");
    InOrderBinaryTreeTraverse(ptree,PrintNode);
    printf("Post Order:\n");
    PostOrderBinaryTreeTraverse(ptree,PrintNode);
    getchar();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值