c++实现二叉树的遍历

来源:互联网 发布:淘宝回收手机 编辑:程序博客网 时间:2024/06/13 08:57

在本例中,创建的树的结构为:


代码如下:

#include <iostream>using namespace std;typedef struct BinaryTreeNode{    char data;    struct BinaryTreeNode *leftChild;    struct BinaryTreeNode *rightChild;}BTNODE, *PBTNODE;PBTNODE CreateBinaryTree();               //创建一个二叉树void PreTraverseBinaryTree(PBTNODE pRoot); //先序遍历二叉树void InTraverseBinaryTree(PBTNODE pRoot);//中序遍历二叉树void PostTraverseBinaryTree(PBTNODE pRoot); //后序遍历二叉树int main(){    PBTNODE pRoot = CreateBinaryTree();    cout << "先序遍历的结果为:";    PreTraverseBinaryTree(pRoot);    cout << endl;    cout << "中序遍历的结果为:";    InTraverseBinaryTree(pRoot);    cout << endl;    cout << "后序遍历的结果为:";    PostTraverseBinaryTree(pRoot);    return 0;}PBTNODE CreateBinaryTree(){    PBTNODE pA = new BTNODE;    PBTNODE pB = new BTNODE;    PBTNODE pC = new BTNODE;    PBTNODE pD = new BTNODE;    PBTNODE pE = new BTNODE;    pA->data = 'A';    pB->data = 'B';    pC->data = 'C';    pD->data = 'D';    pE->data = 'E';    pA->leftChild = pB;    pA->rightChild = pC;    pB->leftChild = NULL;    pB->rightChild = NULL;    pC->leftChild = pD;    pC->rightChild = pE;    pD->leftChild = NULL;    pD->rightChild = NULL;    pE->leftChild = NULL;    pE->rightChild = NULL;    return pA;}void PreTraverseBinaryTree(PBTNODE pRoot){    if(pRoot != NULL)    {        cout << pRoot->data << " ";            //先输出根节点的值        if(pRoot->leftChild != NULL)            PreTraverseBinaryTree(pRoot->leftChild);  //然后遍历根节点的左子树        if(pRoot->rightChild != NULL)            PreTraverseBinaryTree(pRoot->rightChild);  //最后遍历根节点的右子树    }}void InTraverseBinaryTree(PBTNODE pRoot){    if(pRoot != NULL)    {        if(pRoot->leftChild != NULL)            InTraverseBinaryTree(pRoot->leftChild);   //先中序遍历根节点的左子树        cout << pRoot->data << " ";        //再输出根节点的值        if(pRoot->rightChild != NULL)            InTraverseBinaryTree(pRoot->rightChild);   //最后中序遍历根节点的右子树    }}void PostTraverseBinaryTree(PBTNODE pRoot){    if(pRoot != NULL)    {        if(pRoot->leftChild != NULL)            InTraverseBinaryTree(pRoot->leftChild);   //先后序遍历根节点的左子树        if(pRoot->rightChild != NULL)            InTraverseBinaryTree(pRoot->rightChild);   //再后序遍历根节点的右子树        cout << pRoot->data << " ";                    //最后输出根节点的值    }}
运行结果:




0 0