practice1.h文件
#ifndef PRACTICE_H_INCLUDED #define PRACTICE_H_INCLUDED #include <iostream> #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 LevalOrder(); void Visit(TreeNode<T> *currentNode); public: TreeNode<T> *root; }; template<class T> void BinaryTree<T>::InOrder()//中序遍历 左中右 { InOrder(root); } template <class T> void BinaryTree<T>::Visit(TreeNode<T>* currentNode) { std::cout<<currentNode->data; } 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>::LevalOrder()//层序遍历 显示一个之前先把其左右孩子放到队列里 { 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();//出队头 } } #endif // PRACTICE_H_INCLUDED
practice.cpp
#include<iostream> #include "practice1.h" using namespace std; int main() { BinaryTree<char> tree; TreeNode<char> f,g,h,i,a,b,c,d,e; f.data='+'; g.data='-'; h.data='*'; i.data='/'; a.data='A'; b.data='B'; c.data='C'; d.data='D'; e.data='E'; tree.root=&f; f.leftChild=&g; f.rightChild=&e; g.leftChild=&h; g.rightChild=&d; h.leftChild=&i; h.rightChild=&c; i.leftChild=&a; i.rightChild=&b; cout<<"中序遍历"<<endl; tree.InOrder();//中序遍历 cout<<" "<<endl; cout<<"前序遍历"<<endl; tree.PreOrder(); cout<<" "<<endl; cout<<"后序遍历"<<endl; tree.PostOrder(); cout<<" "<<endl; cout<<"层序遍历"<<endl; tree.LevalOrder(); return 0; } //二叉查找树 左边子树都比根节点小 ,右边都比根节点大 //数组实现二叉树 容易造成比较多的空间浪费