【目标】
建立如下所示的一棵二叉树,并且输出其对应的前序遍历、中序遍历、后序遍历。

【代码实现】
// Binarytree.h
#ifndef Binarytree_H
#define Binarytree_H
template
class Binarytree; template
class TreeNode { friend class Binarytree
; private: T data; TreeNode
*rchild; //右指针指向右子树 TreeNode
*lchild; //左指针指向左子树 }; template
class Binarytree { public: Binarytree(){root=0;}; void Creattree2(); void Creattree2(TreeNode
*¤tnode);//使用指针引用建立二叉树 void Preorder(); void Preorder(TreeNode
*currentnode); //前序遍历 void Inorder(); void Inorder(TreeNode
*currentnode); //中序遍历 void Postorder(); void Postorder(TreeNode
*currentnode); //后序遍历 private: TreeNode
*root; }; //--------------先序递归创建二叉树-------- template
void Binarytree
::Creattree2() { Creattree2(root); } template
void Binarytree
::Creattree2(TreeNode
*¤tnode) { //按先序输入二叉树中结点的值(一个字符),空格字符代表空树, char ch; if((ch=getchar())=='#') { currentnode=0; } else { currentnode=new TreeNode
();//产生新的子树 currentnode->data=ch; Creattree2(currentnode->lchild);//递归创建左子树 Creattree2(currentnode->rchild);//递归创建右子树 } } //------递归实现二叉树的前序遍历------ template
void Binarytree
::Preorder() { cout<<前序遍历(根->左->右)为:; Preorder(root); } template
void Binarytree
::Preorder(TreeNode
*currentnode) { if(currentnode) { cout<
data<< ; Preorder(currentnode->lchild); Preorder(currentnode->rchild); } } //------递归实现二叉树的中序遍历------ template
void Binarytree
::Inorder() { cout<<中序遍历(左->根->右)为:; Inorder(root); } template
void Binarytree
::Inorder(TreeNode
*currentnode) { if(currentnode) { Inorder(currentnode->lchild); cout<
data<< ; Inorder(currentnode->rchild); } } //------递归实现二叉树的后序遍历------ template
void Binarytree
::Postorder() { cout<<后序遍历(左->右->根)为:; Postorder(root); } template
void Binarytree
::Postorder(TreeNode
*currentnode) { if(currentnode) { Postorder(currentnode->lchild); Postorder(currentnode->rchild); cout<
data<< ; } } #endif
//main.cpp
#include Binarytree.h
#include
using namespace std; int main() { Binarytree
Tree1; Tree1.Creattree2(); Tree1.Preorder(); cout<
【结果图】

?