二叉树是一种重要的基础数据结构,其定义本身是递归的。二叉树有三种遍历方式,同时既可以利用递归来遍历,又可以利用栈来进行非递归遍历。下面是我个人总结出来的遍历。
首先定义二叉树的结构:
struct BTreeNode
{
char data;
struct BTreeNode* lchild;
struct BTreeNode* rchild;
BTreeNode(char ch) :data(ch), lchild(NULL), rchild(NULL){}
};
一 前序遍历(根->左子树->右子树)
递归遍历:
void pre_order(BTreeNode* p)
{
if (p != NULL)
{
cout << p->data << " ";
pre_order(p->lchild);
pre_order(p->rchild);
}
}
非递归遍历:
void pre_order1(BTreeNode* p)
{
stack<BTreeNode*> s;
if (p == NULL) return;
s.push(p);
while (!s.empty())
{
p = s.top();
s.pop();
cout << p->data << " " << endl;
if (p->rchild) s.push(p->rchild);
if (p->lchild) s.push(p->lchild);
}
}
二 中序遍历(左子树->根->右子树)
递归遍历:
void in_order(BTreeNode* p)
{
if (p != NULL)
{
in_order(p->lchild);
cout << p->data << " ";
in_order(p->rchild);
}
}
非递归遍历:
void in_order1(BTreeNode* p)
{
stack<BTreeNode*> s;
BTreeNode* head = p;
while (!s.empty() || head != NULL)
{
while (head)
{
s.push(head);
head = head->lchild;
}
if (!s.empty())
{
head = s.top();
s.pop();
cout << head->data << " ";
head = head->rchild;
}
}
}
三 后序遍历(左子树->右子树->根)
递归遍历:
void post_order(BTreeNode* p)
{
if (p != NULL)
{
post_order(p->lchild);
post_order(p->rchild);
cout << p->data << " ";
}
}
非递归遍历:
void post_order1(BTreeNode* p)
{
BTreeNode *p1, *q;
q = NULL;
p1 = p;
stack<BTreeNode*> s;
do
{
while (p1)
{
s.push(p1);
p1 = p1->lchild;
}
q = NULL;
while (!s.empty())
{
p1 = s.top();
s.pop();
if (p1->rchild == q)
{
cout << p1->data << " ";
q = p1;
}
else
{
s.push(p1);
p1 = p1->rchild;
break;
}
}
} while (!s.empty());
}