二叉树的三种遍历方式:
typedef struct Node
{
int value;
struct Node* left;
struct Node* right;
}node_t;
1. 前序遍历(根--左--右)
//递归遍历
void preOrderTraverse(node_t* p)
{
if(p != NULL)
{
cout << p->value;
preOrderTraverse(p->left);
preOrderTraverse(p->right);
}
}
//非递归遍历
void preOrderTraverse(node_t* p)
{
stack<node_t *> s;
initStack(s);
s.push(p);
node_t* tmp = NULL;
while(!s.empty())
{
tmp = s.pop();
while(tmp != NULL)
{
cout << tmp->value;
if(tmp->right)
s.push(tmp->right);
tmp = tmp->left;
}
}
}
2. 中序遍历(左--根--右)
//递归遍历
void inOrderTraverse(node_t* p)
{
if(p != NULL)
{
inOrderTraverse(p->left);
cout << p->value;
inOrderTraverse(p->right);
}
}
//非递归遍历void inOrderTraverse(node_t* p)
{
stack<node_t*> s;
initStack(s);
node_t* tmp = p;
while(tmp || !s.empty())
{
while(tmp)
{
s.push(p);
p = p->left;
}
tmp = s.pop();
cout << tmp->value;
tmp = tmp->right;
}
}
3. 后序遍历(左--右--根)
//递归遍历
void postOrderTraverse(node_t* p)
{
if(p)
{
postOrderTraverse(p->left);
postOrderTraverse(p->right);
cout << p->value;
}
}
//非递归遍历
void postOrderTraverse(node_t* p)
{
node_t* tmp = p;
node_t* q = NULL;
stack<node_t*> s;
initStack(s);
while(tmp || !s.empty())
{
while(tmp)
{
s.push(tmp);
if(tmp->left)
tmp = tmp->left;
else
tmp = tmp->right;
}
if(s.empty())
break;
q = s.top();
if(q->right == tmp)
{
tmp = s.pop();
cout << tmp->value;
}
else
{
tmp = q->right;
}
}
}