如图所示:
前序遍历:先访问根节点,再访问左子树,最后访问右子树,上图所示的前序遍历是:8,6,5,7,10,9,11.
中序遍历:先访问左子树,再访问根节点,最后访问右子树,上图所示的中序遍历是:5,6,7,8,9,10,11.
后序遍历:先访问左子树,再访问右子树,最后访问根节点,上图所示的后序遍历是:5,7,6,9,11,10,8.
前序遍历实现的非递归代码:
#include<iostream>
#include<stack>
using namespace std;
struct TreeNode
{
int value;
TreeNode* left;
TreeNode* right;
TreeNode(int x)
:value(NULL)
, left(NULL)
, right(NULL)
{}
};
void PrevOrderNonR(TreeNode* root)
{
TreeNode* cur = NULL;
stack<TreeNode*> s;
while (cur || !s.empty())
{
while (cur)
{
cout << cur->value << "";
s.push(cur);
cur = cur->left;
}
TreeNode* top = s.top();
s.pop();
cur = top->right;
}
cout << endl;
}
中序遍历的代码:
void InOrderNonR(TreeNode* root)
{
TreeNode* cur = root;
stack<TreeNode*>s;
while (cur || !s.empty())
{
while (cur)
{
s.push(cur);
cur = cur->left;
}
TreeNode* top = s.top();
s.pop();
cout << top->right << "";
cur = top->right;
}
cout << endl;
}
后序遍历的代码:
void PostOrNonR(TreeNode* root)
{
TreeNode* pre = NULL;
TreeNode* cur = root;
stack<TreeNode*>s;
while (cur || !s.empty())
{
while (cur)
{
s.push(cur);
cur = cur->left;
}
TreeNode* top = s.top();
if (top->right == NULL || top->right == pre)
{
cout << top->value << "";
pre = top;
s.pop();
}
else
{
cur = top->right;
}
}
}