1、构建一个简单的队列操作
class CQueue { public: void Push(CTreeNode<int>*); CTreeNode<int>* Pop(); BOOL IsEmpty(); private: CStack<int> stack_1; CStack<int> stack_2; }; void CQueue::Push(CTreeNode<int>* p) { stack_1.Push(p); } CTreeNode<int>* CQueue::Pop() { if (stack_2.IsEmpty()) { while (!stack_1.IsEmpty()) { stack_2.Push(stack_1.Pop()); } } return stack_2.Pop(); } BOOL CQueue::IsEmpty() { return stack_1.IsEmpty() && stack_2.IsEmpty(); }
2、层次遍历算法
void LevelTraverse(CTreeNode<int>* pTreeNode) { printf(" "); CQueue queue; if (!pTreeNode) { return; } queue.Push(pTreeNode); while (!queue.IsEmpty()) { pTreeNode = queue.Pop(); if (!pTreeNode) { continue; } printf("Level:%d ", pTreeNode->nData); queue.Push(pTreeNode->pLChild); queue.Push(pTreeNode->pRChild); } }