|
#pragma once
using namespace std;
#include<iostream>
#include<string>
template<class NodeType>
class MyTreeNode
{
public:
typedef struct BTNode
{
NodeType _data;
struct BTNode *_lchild;
struct BTNode *_rchild;
}BTNode,*BTNodePtr;
MyTreeNode()
{
_root = new BTNode();
_root->_lchild = NULL;
_root->_rchild = NULL;
}
void PreOrderCreateBinaryTree()
{
PreOrderCreateBinaryTree(_root);
}
void PreOrder()
{
PreOrder(visit,_root);
}
private:
static void visit(BTNodePtr root) ----------------这里为什么要加static
{
cout << root->_data<<endl;
}
void PreOrderCreateBinaryTree(BTNodePtr& root)
{
int node;
cout << "请输入结点:" << endl;
cin >> node;
if(node != -1)
{
if(!root)
root = new BTNode();
root->_data = node;
PreOrderCreateBinaryTree(root->_lchild);
PreOrderCreateBinaryTree(root->_rchild);
}
}
void PreOrder(void (*p_visit)(BTNodePtr t),BTNodePtr root)
{
if(root)
{
p_visit(root);
PreOrder(p_visit,root->_lchild);
PreOrder(p_visit,root->_rchild);
}
}
BTNodePtr _root;
};
----------------------------------------------------------------------------------------------
#include<iostream>
#include<string>
#include"MyTreeNode.h"
using namespace std;
void main()
{
MyTreeNode<int> BTree;
BTree.PreOrderCreateBinaryTree();
BTree.PreOrder();
system("pause");
} |
|