二叉树遍历:
访问节点:
void Visit(BTNode* pNode)
{
std::cout << pNode->nData << " ";
}
前序遍历:
// 前序遍历(递归)
void PreOrderTraverse1(BTNode* pRoot)
{
if (NULL == pRoot)
return;
Visit(pRoot);
PreOrderTraverse1(pRoot->pLeft);
PreOrderTraverse1(pRoot->pRight);
}
// 前序遍历(非递归)
void PreOrderTraverse2(BTNode* pRoot)
{
if (NULL == pRoot)
return;
BTNode * pCur =pRoot;
std::stack<BTNode*> myStack;
while (pCur != NULL || !myStack.empty())
{
while (pCur != NULL) // 将所有左子树入栈
{
Visit(pCur);
myStack.push(pCur);
pCur = pCur->pLeft;
}
if (!myStack.empty()) // 取栈顶元素,对其右子树进行处理
{
pCur = myStack.top();
myStack.pop();
pCur = pCur->pRight;
}
}
}
// 前序遍历(非递归)
void PreOrderTraverse3(BTNode* pRoot)
{
if (NULL == pRoot)
return;
BTNode* pCur = NULL;
std::stack<BTNode*> myStack;
myStack.push(pRoot);
while (!myStack.empty())
{
pCur = myStack.top();
Visit(pCur);
myStack.pop();
// 先入栈右子树
if (pCur->pRight != NULL)
myStack.push(pCur->pRight);
// 后入栈左子树
if (pCur->pLeft != NULL)
myStack.push(pCur->pLeft);
}
}
// 中序遍历(非递归)
void InOrderTraverse2(BTNode* pRoot)
{
if (NULL == pRoot)
return;
BTNode* pCur = pRoot;
std::stack<BTNode*> myStack;
while (pCur != NULL || !myStack.empty())
{
// 将当前节点的左子树入栈
while (pCur != NULL)
{
myStack.push(pCur);
pCur = pCur->pLeft;
}
if (! myStack.empty())
{
pCur = myStack.top();
myStack.pop();
Visit(pCur);
pCur = pCur->pRight;
}
}
}
后序遍历:
// 后序遍历(递归)
void PostOrderTraverse1(BTNode* pRoot)
{
if (NULL == pRoot)
return;
PostOrderTraverse1(pRoot->pLeft);
PostOrderTraverse1(pRoot->pRight);
Visit(pRoot);
}
// 后序遍历(非递归)
void PostOrderTraverse2(BTNode* pRoot)
{
if (NULL == pRoot)
return;
BTNode* pCur = NULL;
BTNode* pPre = NULL; // 用来标识前一个访问节点
std::stack<BTNode*> myStack;
myStack.push(pRoot); // 入栈根节点
while (!myStack.empty())
{
pCur = myStack.top();
// 如果左右子树为空,或者左右子树均已访问
if (NULL == pCur->pLeft && NULL == pCur->pRight ||
pPre != NULL && (pPre == pCur->pLeft || pPre == pCur->pRight))
{
Visit(pCur);
myStack.pop();
pPre = pCur; // 标识pCur节点已访问
}
else
{
/*先入栈右子树,再入栈左子树。出栈的时候才能先访问左子树,在访问右子树*/
if (pCur->pRight != NULL)
myStack.push(pCur->pRight);
if (pCur->pLeft != NULL)
myStack.push(pCur->pLeft);
}
}
}
层序遍历:
// 层序遍历
void LevelOrderTraverse(BTNode* pRoot)
{
if (NULL == pRoot)
return;
BTNode* pCur = NULL;
std::queue<BTNode*> myQueue;
myQueue.push(pRoot); // 先将根节点入队
while (!myQueue.empty())
{
pCur = myQueue.front(); // 取队首节点
Visit(pCur);
myQueue.pop();
if (pCur->pLeft != NULL) // 入队左子树
myQueue.push(pCur->pLeft);
if (pCur->pRight != NULL) // 入队右子树
myQueue.push(pCur->pRight);
}
}
参考文章: