树-01_二叉树

树-01_二叉树

  • 一、说明
  • 二、代码
        • main.cpp
        • BinaryTree.h
        • 输出结果

一、说明

树-01_二叉树_第1张图片

二、代码

main.cpp

#include 
#include "BinaryTree.h"

using namespace std;

int main()
{
    cout << "二叉树:" << endl;
    BinaryTree tree;
    TreeNode A,B,C,D,a,b,c,d,e;
    A.data = '+';
    B.data = '-';
    C.data = '*';
    D.data = '/';
    a.data = 'A';
    b.data = 'B';
    c.data = 'C';
    d.data = 'D';
    e.data = 'E';

    tree.root = &A;
    A.leftChild = &B;
    A.rightChild = &e;
    B.leftChild = &C;
    B.rightChild = &d;
    C.leftChild = &D;
    C.rightChild = &c;
    D.leftChild = &a;
    D.rightChild = &b;

    cout<<"前序遍历:"<

BinaryTree.h

#ifndef BINARYTREE_H
#define BINARYTREE_H

#include
#include//C++标准模版库队列

using namespace std;

template  class BinaryTree;

/*二叉树节点类*/
template 
class TreeNode
{
public:
    TreeNode()
    {
        leftChild = NULL;
        rightChild = NULL;
    }

    Type data;//数据域
    TreeNode *leftChild;//左孩子
    TreeNode *rightChild;//右孩子
};

/*二叉树类*/
template 
class BinaryTree
{
public:
    TreeNode *root;//用一个指针指向树根节点

public:
    void PreOrder();//前序遍历
    void PreOrder(TreeNode *currentNode);
    void InOrder();//中序遍历
    void InOrder(TreeNode *currentNode);
    void PostOrder();//后序遍历
    void PostOrder(TreeNode *currentNode);
    void LevelOrder();//层序遍历
    void Visit(TreeNode *currnetNode);//显示当前节点
};

/*二叉树类:前序遍历函数*/
template
void BinaryTree::PreOrder()
{
    PreOrder(root);
}

/*二叉树类:前序遍历重载函数*/
template 
void BinaryTree::PreOrder(TreeNode *currentNode)
{
    if(currentNode)
    {
        Visit(currentNode);
        PreOrder(currentNode->leftChild);
        PreOrder(currentNode->rightChild);
    }
}

/*二叉树类:中序遍历函数*/
template
void BinaryTree::InOrder()
{
    InOrder(root);
}

/*二叉树类:中序遍历重载函数*/
template
void BinaryTree::InOrder(TreeNode *currentNode)
{
    if(currentNode)
    {
        InOrder(currentNode->leftChild);
        Visit(currentNode);
        InOrder(currentNode->rightChild);
    }
}

/*二叉树类:后续遍历函数*/
template
void BinaryTree::PostOrder()
{
    PostOrder(root);
}

/*二叉树类:后序遍历重载函数*/
template
void BinaryTree::PostOrder(TreeNode *currentNode)
{
    if(currentNode)
    {
        PostOrder(currentNode->leftChild);
        PostOrder(currentNode->rightChild);
        Visit(currentNode);
    }
}

/*二叉树类:层序遍历*/
template
void BinaryTree::LevelOrder()
{
    queue*> q;//声明一个节点结构的队列
    TreeNode *currentNode = root;
    while(currentNode)
    {
        Visit(currentNode);
        if(currentNode->leftChild)
        {
            q.push(currentNode->leftChild);
        }
        if(currentNode->rightChild)
        {
            q.push(currentNode->rightChild);
        }
        if(q.empty())
        {
            return ;
        }
        currentNode = q.front();
        q.pop();
    }
}

/*二叉树类:当前节点输出函数*/
template
void BinaryTree::Visit(TreeNode *currentNode)
{
    cout<data;
}

#endif // BINARYTREE_H

输出结果

树-01_二叉树_第2张图片

你可能感兴趣的:(数据结构--C++描述,C++,二叉树)