1、构建二叉树的代码
这里为了方便,暂时没用T data。
template <typename T> class CTreeNode { public: CTreeNode(); ~CTreeNode(); public: T data; int nData; CTreeNode* pLChild; CTreeNode* pRChild; }; template <typename T> CTreeNode<T>::~CTreeNode() { } template <typename T> CTreeNode<T>::CTreeNode() : nData(0), pLChild(NULL), pRChild(NULL) { }
构建二叉树:
template <typename T> void BuildBinTree(int i, CTreeNode<T>** ppTreeNode) { if (i < _countof(g_szArray)) { *ppTreeNode = new(CTreeNode<T>); (*ppTreeNode)->nData = g_szArray[i]; printf("%d ", g_szArray[i]); } else { return; } if (2 * i + 1 < _countof(g_szArray)) { printf("l:"); BuildBinTree(2 * i + 1, &(*ppTreeNode)->pLChild); } if (2 * i + 2 < _countof(g_szArray)) { printf("r:"); BuildBinTree(2 * i + 2, &(*ppTreeNode)->pRChild); } }
2、构建一个简单的栈的代码:
template <typename T> class CStack { public: CStack(); ~CStack(); void Push(CTreeNode<T>*); CTreeNode<T>* Pop(); BOOL IsEmpty(); private: CTreeNode<T>** m_szTreeNodeArray; int m_nSize; int m_nCapacity; }; template <typename T> BOOL CStack<T>::IsEmpty() { return !m_nSize; } template <typename T> CTreeNode<T>* CStack<T>::Pop() { return m_szTreeNodeArray[--m_nSize]; } template <typename T> void CStack<T>::Push(CTreeNode<T>* pTreeNode) { if (!pTreeNode) { return; } if (!m_szTreeNodeArray) { return; } if (m_nSize > m_nCapacity) { //realloc } m_szTreeNodeArray[m_nSize++] = pTreeNode; } template <typename T> CStack<T>::CStack() : m_nSize(0), m_nCapacity(INIT_STACK_CAPACITY), m_szTreeNodeArray(NULL) { m_szTreeNodeArray = new CTreeNode<T>*[INIT_STACK_CAPACITY]; if (!m_szTreeNodeArray) { return; } } template <typename T> CStack<T>::~CStack() { if (m_szTreeNodeArray) { free(m_szTreeNodeArray); } }
3、非递归遍历的逻辑
CStack<int> g_stack; template <typename T> void NonRecursiveTraverse(CTreeNode<T>* pTreeNode) { while (true) { while (pTreeNode) { printf("Visit Node:%d ", pTreeNode->nData); g_stack.Push(pTreeNode->pRChild); pTreeNode = pTreeNode->pLChild; } if (g_stack.IsEmpty()) { break; } if (!g_stack.IsEmpty()) { pTreeNode = g_stack.Pop(); } } }
4、main函数
#define INIT_STACK_CAPACITY 50 int g_szArray[] = { 1, 3, 2, 4, 7, 5, 6, 8 }; void main() { CTreeNode<int>* pTreeNode = NULL; BuildBinTree<int>(0, &pTreeNode); printf(" Non recurisive traverse: "); NonRecursiveTraverse(pTreeNode); getchar(); }
5、运行结果