树集成了数组和链表的优点(查找速度快)
树:结点,度,叶结点,父结点,子结点,兄弟结点,树的度,树的高度。
具体概念可以参考:https://blog.csdn.net/u012928324/article/details/61194190?utm_source=itdadao&utm_medium=referral
#ifndef _BinaryTree_H__
#define _BinaryTree_H__
#include<iostream>
#include <queue>
using namespace std;
template<class T> class Binary_Tree;
template <class T>
class TreeNode //树节点
{
public:
TreeNode()
{
leftchild=rightchild=NULL;
}
T data; //数据
TreeNode<T>* leftchild; //左孩子
TreeNode<T>*rightchild; //右孩子
};
template <class T>
class Binary_Tree //树
{
public:
void InOrder(); //中序遍历 左子树-节点-右子树
void PreOrder(); //前序遍历 节点-左子树-右子树
void PostOrder(); //后序遍历 左子树-右子树-节点
void LevelOrder(); //层序遍历
void InOrder(TreeNode<T>*CurrentNode); //显示当前节点
void PreOrder(TreeNode<T>*CurrentNode);
void PostOrder(TreeNode<T>*CurrentNode);
void Vivit(TreeNode<T>*CurrentNode);
TreeNode<T>*root; //根
};
template<class T>
void Binary_Tree<T>::InOrder() //中序遍历 左子树-节点-右子树
{
InOrder(root);
}
template<class T>
void Binary_Tree<T>::Vivit(TreeNode<T>*CurrentNode)//显示节点或处理数据
{
cout<<CurrentNode->data;
}
template<class T>
void Binary_Tree<T>::InOrder(TreeNode<T>*CurrentNode)
{
if(CurrentNode) //如果当前节点不为空
{
InOrder(CurrentNode->leftchild); //先遍历左节点
Vivit(CurrentNode); //显示当前节点
InOrder(CurrentNode->rightchild); //再遍历右节点
}
}
template<class T>
void Binary_Tree<T>::PreOrder() //前序
{
PreOrder(root);
}
template<class T>
void Binary_Tree<T>::PreOrder(TreeNode<T>*CurrentNode)//前序遍历
{
if(CurrentNode)
{
Vivit(CurrentNode);
PreOrder(CurrentNode->leftchild); //左边
PreOrder(CurrentNode->rightchild); //右边
}
}
template<class T>
void Binary_Tree<T>::PostOrder() //后序遍历
{
PostOrder(root);
}
template<class T>
void Binary_Tree<T>::PostOrder(TreeNode<T>*CurrentNode)//后序遍历
{
if(CurrentNode)
{
PostOrder(CurrentNode->leftchild);
PostOrder(CurrentNode->rightchild);
Vivit(CurrentNode);
}
}
template<class T>
void Binary_Tree<T>::LevelOrder() //层序遍历
{
queue<TreeNode<T>*> q;
TreeNode<T> *currentNode=root;
while(currentNode)
{
Vivit(currentNode);
if(currentNode->leftchild) q.push(currentNode->leftchild); //如果左节点存在,则放入队列中
if(currentNode->rightchild) q.push(currentNode->rightchild);
if(q.empty()) return; //如果为空 则结束
currentNode=q.front();
q.pop(); //删除显示出的数据
}
}
#endif // _BinaryTree_H__
main
#include <iostream>
#include "BinaryTree.h"
using namespace std;
int main()
{
Binary_Tree<char> P;
TreeNode<char> add,sub,mul,div,a,b,c,d,e,tree;;
add.data='+';
sub.data='-';
mul.data='*';
div.data='/';
a.data='A';
b.data='B';
c.data='C';
d.data='D';
e.data='E';
P.root=&add;
add.leftchild=⊂
add.rightchild=&e;
sub.leftchild=&mul;
sub.rightchild=&d;
mul.leftchild=÷
mul.rightchild=&c;
div.leftchild=&a;
div.rightchild=&b;
cout << "中序遍历:";
P.InOrder(); //中序遍历
cout<<endl;
//
cout << "前序遍历:";
P.PreOrder(); //中序遍历
cout<<endl;
cout << "后序遍历:";
P.PostOrder(); //中序遍历
cout<<endl;
cout << "层序遍历:";
P.LevelOrder();
return 0;
}