//先序遍历--非递归版本
//1.取当前结点--访问结点--出栈
//2.保存右子树
//3.保存左子树
void PreOrder_Nor()
{
cout << "PreOrder_Nor: " << endl;
if (NULL == _pRoot)
return;
stack<Node*> s;
s.push(_pRoot);
while (!s.empty())
{
Node* pCur = s.top();
s.pop();
while (pCur)
{
//访问结点
cout << pCur->_data << " ";
//保存右子树
if (pCur->_pRight)
s.push(pCur->_pRight);
//保存左子树
pCur = pCur->_pLeft;
}
pCur = NULL;
}
cout << endl;
}
//中序遍历: 非递归版本
//1.while() -->找最左边的结点---保存所经路径上的所有结点
//2.访问当前结点pCur -->出栈
//3.当前结点右子树是否存在, pCur->right 1-->存在,循环 2-->不存在,取栈顶
void InOrder_Nor()
{
cout << "Inorder_Nor: " << endl;
if (NULL == _pRoot)
return;
stack<Node*> s;
Node* pCur = _pRoot;
while(pCur || !s.empty())
{
while(pCur)
{
s.push(pCur);
pCur = pCur->_pLeft;
}
pCur = s.top();
cout << pCur->_data << " ";
s.pop();
pCur = pCur->_pRight;
}
cout << endl;
}
//后序遍历的非递归版本
void PostOrder_Nor()
{
if (NULL == _pRoot)
return;
stack<Node*> s;
Node* pCur = _pRoot; //指针指向根的位置
Node* prev = NULL;
while(pCur || !s.empty()) //栈判空
{
//找最左边的结点,保存所经路径上的所有结点
while(pCur)
{
s.push(pCur);
pCur = pCur->_pLeft;
}
pCur = s.top(); //取栈顶
if (NULL == pCur->_pRight || prev == pCur->_pRight) //查看右子树是否存在
{ // 不存在,访问结点,出栈
cout << pCur->_data << " ";
prev = pCur;
s.pop();
pCur = NULL; //pCur置空
}
else
pCur = pCur->_pRight;
}
cout << endl;
}