建立如下所示的一棵二叉树,并且输出其对应的前序遍历、中序遍历、后序遍历。
建立二叉树以及实现遍历的操作存放在Binarytree.h文件中
//Binarytree.h
#ifndef Binarytree_H
#define Binarytree_H
template<class T> class Binarytree;
template<class T>
class TreeNode
{
friend class Binarytree<T>;
private:
T data;
TreeNode<T> *rchild; //右指针指向右子树
TreeNode<T> *lchild; //左指针指向左子树
};
template<class T>
class Binarytree
{
public:
Binarytree(){root=0;};
void CreatTree(); //根据实际情况建立二叉树
void Preorder();
void Preorder(TreeNode<T> *currentnode); //前序遍历
void Inorder();
void Inorder(TreeNode<T> *currentnode); //中序遍历
void Postorder();
void Postorder(TreeNode<T> *currentnode); //后序遍历
private:
TreeNode<T> *root;
};
//-------建立二叉树--------
template<class T>
void Binarytree<T>::CreatTree()
{
TreeNode<T> *p1=new TreeNode<T>();
p1->data=‘A‘;
p1->rchild=0;
p1->lchild=0;
root=p1;
TreeNode<T> *p2=new TreeNode<T>();
p2->data=‘B‘;
p2->rchild=0;
p2->lchild=0;
root->lchild=p2;
TreeNode<T> *p3=new TreeNode<T>();
p3->data=‘C‘;
p3->rchild=0;
p3->lchild=0;
root->rchild=p3;
TreeNode<T> *p4=new TreeNode<T>();
p4->data=‘D‘;
p4->rchild=0;
p4->lchild=0;
root->lchild->lchild=p4;
TreeNode<T> *p5=new TreeNode<T>();
p5->data=‘E‘;
p5->rchild=0;
p5->lchild=0;
root->lchild->rchild=p5;
TreeNode<T> *p6=new TreeNode<T>();
p6->data=‘F‘;
p6->rchild=0;
p6->lchild=0;
root->rchild->lchild=p6;
TreeNode<T> *p7=new TreeNode<T>();
p7->data=‘G‘;
p7->rchild=0;
p7->lchild=0;
root->rchild->rchild=p7;
TreeNode<T> *p8=new TreeNode<T>();
p8->data=‘H‘;
p8->rchild=0;
p8->lchild=0;
root->lchild->lchild->lchild=p8;
TreeNode<T> *p9=new TreeNode<T>();
p9->data=‘I‘;
p9->rchild=0;
p9->lchild=0;
root->lchild->lchild->rchild=p9;
}
//------递归实现二叉树的前序遍历------
template<class T>
void Binarytree<T>::Preorder()
{
cout<<"前序遍历(根->左->右)为:";
Preorder(root);
}
template<class T>
void Binarytree<T>::Preorder(TreeNode<T> *currentnode)
{
if(currentnode)
{
cout<<currentnode->data<<" ";
Preorder(currentnode->lchild);
Preorder(currentnode->rchild);
}
}
//------递归实现二叉树的中序遍历------
template<class T>
void Binarytree<T>::Inorder()
{
cout<<"中序遍历(左->根->右)为:";
Inorder(root);
}
template<class T>
void Binarytree<T>::Inorder(TreeNode<T> *currentnode)
{
if(currentnode)
{
Inorder(currentnode->lchild);
cout<<currentnode->data<<" ";
Inorder(currentnode->rchild);
}
}
//------递归实现二叉树的后序遍历------
template<class T>
void Binarytree<T>::Postorder()
{
cout<<"后序遍历(左->右->根)为:";
Postorder(root);
}
template<class T>
void Binarytree<T>::Postorder(TreeNode<T> *currentnode)
{
if(currentnode)
{
Postorder(currentnode->lchild);
Postorder(currentnode->rchild);
cout<<currentnode->data<<" ";
}
}
#endif
主程序:
//main.cpp
#include "Binarytree.h"
#include <iostream>
using namespace std;
int main()
{
Binarytree<char> Tree1;
Tree1.CreatTree();
Tree1.Preorder();
cout<<endl;
Tree1.Inorder();
cout<<endl;
Tree1.Postorder();
cout<<endl;
system("pause");
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/adminabcd/article/details/46775925