遍历:遵循某种次序,遍历二叉树中的所有节点,使得每个结点被访问一次,而且仅访问(对节点进行特定操作)一次。
// 二叉树的遍历
//递归
//前序遍历
void _PreOrder(Node* _pRoot)
{
if (_pRoot)
{
cout << _pRoot->_value << " ";
_PreOrder(_pRoot->_pLeft);
_PreOrder(_pRoot->_pRight);
}
}
//非递归
//利用栈实现
void _PreOrder_Nor()
{
if (NULL == _pRoot)
return;
stack<Node*> s;
s.push(_pRoot);
while (!s.empty())
{
Node* cur = s.top();
cout << cur->value << " ";
s.pop();
if (cur->_pRight)
//?
s.push(cur->_pRight);
if (cur->_pleft)
s.push(cur->_pLeft);
}
}
//中序遍历
//递归,先遍历左子树,再根,再右子树
void _InOrder(Node* pRoot)
{
if (pRoot)
{
_InOrder(pRoot->_pLeft);
cout << pRoot->_value << " ";
_InOrder(pRoot->_pRight);
}
}
//非递归
//栈实现
void _InOrder_Nor()
{
if (_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->_value << " ";
s.pop();
//右不存在
if (NULL == pCur->_pRight && s.empty())
{
pCur = s.top();
cout << pCur->_value << " ";
s.pop();
}
pCur = pCur->_pRight;
}
}
//后序遍历
//递归
void _PostOrder(Node* pRoot)
{
if (NULL == pRoot)
return;
_PostOrder(pRoot->_pRight);
_PostOrder(pRoot->_pLeft);
cout << pRoot->_value << " ";
}
//非递归,栈实现
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;
}
Node* pTop = s.top();
//处理左单支
if (NULL == pTop->_pRight || pTop->_pRight = prev)
{
cout << pTop->_value << " ";
prev = pTop;
s.pop();
}
else
pCur = pTop->_pRight;
}
}
// 层序遍历
void LevelOrder()
{
if (NULL == _pRoot)
return;
queue<Node*> q;
q.push(_pRoot);
while (!q.empty())
{
Node* pCur = q.front();
q.pop();
if (pCur->_pLeft)
q.push(pCur->_pLeft);
if (pCur->_pRight)
q.push(pCur->_pRight);
cout << pCur->_value << " ";
}
cout << endl;
}
“`