// Algorithm.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <functional>
#define D_LEFT 0
#define D_RIGHT 1
template <class T>
struct BNode
{
BNode() :pLNode(NULL), pRNode(NULL), pValue(NULL) {}
BNode* pLNode; // 左子树
BNode* pRNode; // 右子树
T* pValue; // 值
};
template<class T>
class BTree
{
public:
BTree():root(NULL){}
void Insert(T* pValue)
{
BNode<T>* pNode = new BNode<T>();
pNode->pValue = pValue;
// 如果树为空
if(NULL == root)
{
root = pNode;
return;
}
int iInsertFlag = 0; // 插入方向,左还是右
BNode<T>* pParent = NULL;
BNode<T>* pTem = root;
while(pTem)
{
pParent = pTem;
if(*pNode->pValue < *pTem->pValue)
{
iInsertFlag = D_LEFT;
pTem = pTem->pLNode;
}
else
{
iInsertFlag = D_RIGHT;
pTem = pTem->pRNode;
}
}
if(pParent)
{
switch(iInsertFlag)
{
case D_LEFT:
pParent->pLNode = pNode;
break;
case D_RIGHT:
pParent->pRNode = pNode;
break;
default:
break;
}
}
}
// 先访问 根->左->右
// 前序遍历
void DLR(BNode<T>* root,std::function<void (T*)> _callback)
{
// 空树
if(NULL == root)
{
return;
}
_callback(root->pValue);
if(root->pLNode != NULL)
DLR(root->pLNode,_callback);
if(root->pRNode != NULL)
DLR(root->pRNode,_callback);
}
// 先访问 左->根->右
// 中序遍历
void LDR(BNode<T>* root, std::function<void(T*)> _callback)
{
// 空树
if(NULL == root)
{
return;
}
if(root->pLNode != NULL)
LDR(root->pLNode, _callback);
_callback(root->pValue);
if(root->pRNode != NULL)
LDR(root->pRNode, _callback);
}
// 先访问 左->右->根
// 后序遍历
void LRD(BNode<T>* root, std::function<void(T*)> _callback)
{
// 空树
if(NULL == root)
{
return;
}
if(root->pLNode != NULL)
LRD(root->pLNode, _callback);
if(root->pRNode != NULL)
LRD(root->pRNode, _callback);
_callback(root->pValue);
}
public:
BNode<T>* root;
};
int main()
{
BTree<int> bTree;
int a[5] = { 2,5,1,1,3 };
bTree.Insert(&a[0]);
bTree.Insert(&a[1]);
bTree.Insert(&a[2]);
bTree.Insert(&a[3]);
bTree.Insert(&a[4]);
// 打印前序遍历
printf("前序遍历:\n");
bTree.DLR(bTree.root, [](int* a)
{
printf("%d ", *a);
});
printf("\n\n中序遍历:\n");
// 打印中序遍历
bTree.LDR(bTree.root, [](int* a)
{
printf("%d ", *a);
});
printf("\n\n后续遍历:\n");
// 打印中序遍历
bTree.LRD(bTree.root, [](int* a)
{
printf("%d ", *a);
});
getchar();
return 0;
}