BinaryTree.h:
#pragma once
#include <queue>
template<class T>
class BinaryTree;
template<class T>
class TreeNode
{
public:
TreeNode() :leftChild(NULL), rightChild(NULL)
{
}
T data;
TreeNode<T> *leftChild;//左节点
TreeNode<T> *rightChild;//右节点
};
template<class T>
class BinaryTree
{
public:
//二叉树可以进行的操作
void InOrder();//中序遍历
void InOrder(TreeNode<T> *currentNode);
void PreOrder();//前序遍历
void PreOrder(TreeNode<T> *currentNode);
void PostOrder();//后序遍历
void PostOrder(TreeNode<T> *currentNode);
void LevelOrder();//层序遍历
void LevelOrder(TreeNode<T> *currentNode);
void Visit(TreeNode<T> *currentNode);
public:
TreeNode<T> *root;
};
template<class T>
void BinaryTree<T>::Visit(TreeNode<T> *currentNode)
{
std::cout << currentNode->data;
}
//中序遍历---左子树,节点,右子树
template<class T>
void BinaryTree<T>::InOrder()
{
InOrder(root);
}
template<class T>
void BinaryTree<T>::InOrder(TreeNode<T> *currentNode)
{
if (currentNode)//如果节点不为空
{
//递归
InOrder(currentNode->leftChild);
//显示当前节点
Visit(currentNode);
InOrder(currentNode->rightChild);
}
}
//前序遍历---节点,左子树,右子树
template<class T>
void BinaryTree<T>::PreOrder()
{
PreOrder(root);
}
template<class T>
void BinaryTree<T>::PreOrder(TreeNode<T> *currentNode)
{
if (currentNode)//如果节点不为空
{
//显示当前节点
Visit(currentNode);
//递归
PreOrder(currentNode->leftChild);
PreOrder(currentNode->rightChild);
}
}
//后序遍历---左子树,右子树,节点
template<class T>
void BinaryTree<T>::PostOrder()
{
PostOrder(root);
}
template<class T>
void BinaryTree<T>::PostOrder(TreeNode<T> *currentNode)
{
if (currentNode)//如果节点不为空
{
//递归
PostOrder(currentNode->leftChild);
PostOrder(currentNode->rightChild);
//显示当前节点
Visit(currentNode);
}
}
//层序遍历---
template<class T>
void BinaryTree<T>::LevelOrder()
{
std::queue<TreeNode<T>*> q;
TreeNode<T>* 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<class T>
void BinaryTree<T>::LevelOrder(TreeNode<T> *currentNode)
{
if (currentNode)//如果节点不为空
{
//递归
InOrder(currentNode->leftChild);
InOrder(currentNode->rightChild);
//显示当前节点
Visit(currentNode);
}
}
Main.cpp:
#include <iostream>
#include "BinaryTree.h"
int main()
{
BinaryTree<char> tree;
TreeNode<char> plus, minus, multi, divide, a, b, c, d, e;
plus.data = '+';
minus.data = '-';
multi.data = '*';
divide.data = '/';
a.data = 'A';
b.data = 'B';
c.data = 'C';
d.data = 'D';
e.data = 'E';
tree.root = +
plus.leftChild = −
plus.rightChild = &e;
minus.leftChild = &multi;
minus.rightChild = &d;
multi.leftChild = ÷
multi.rightChild = &c;
divide.leftChild = &a;
divide.rightChild = &b;
tree.InOrder();//中序遍历
std::cout << std::endl;
tree.PreOrder();//前序遍历
std::cout << std::endl;
tree.PostOrder();//后序遍历
std::cout << std::endl;
tree.LevelOrder();//层序遍历
std::cout << std::endl;
return 0;
}