二叉树的遍历
1.树的结构
2.递归遍历过程
3.非递归过程
4.实现
1.递归实现
void PreOrder(BtNode* p)
{
if (p != NULL)
{
cout << p->data << " ";
PreOrder(p->leftchild);
PreOrder(p->rightchild);
}
}
2.非递归实现
void NicePreOrder(BtNode* ptr)
{
if (ptr == NULL) return;
stack<BtNode*> st;
st.push(ptr);
while (!st.empty())
{
ptr = st.top();
st.pop();
cout << ptr->data << " ";
if (ptr->rightchild)
{
st.push(ptr->rightchild);
}
if (ptr->leftchild)
{
st.push(ptr->leftchild);
}
}
}
5.完整代码
#include <iostream>
#include <stack>
using namespace std;
typedef char ElemType;
typedef struct BtNode
{
ElemType data;
struct BtNode* leftchild;
struct BtNode* rightchild;
}BtNode, * BinaryTree;
//非递归实现先序遍历
void NicePreOrder(BtNode* ptr)
{
if (ptr == NULL) return;
stack<BtNode*> st;
st.push(ptr);
while (!st.empty())
{
ptr = st.top();
st.pop();
cout << ptr->data << " ";
if (ptr->rightchild)
{
st.push(ptr->rightchild);
}
if (ptr->leftchild)
{
st.push(ptr->leftchild);
}
}
}
//递归实现二叉树的先序遍历
void PreOrder(BtNode* p)
{
if (p != NULL)
{
cout << p->data << " ";
PreOrder(p->leftchild);
PreOrder(p->rightchild);
}
}
//---------------二叉树的构建--------------
BtNode* BuyNode()
{
BtNode* s = (BtNode*)malloc(sizeof(BtNode));
if (NULL == s) exit(1);
memset(s, sizeof(BtNode), 0);
}
//先构造左子树,再构造右子树
BtNode* CBTree()
{
BtNode* s = NULL;
ElemType elem;
cin >> elem;
if (elem != '#')
{
s = BuyNode();
s->data = elem;
s->leftchild = CBTree();
s->rightchild = CBTree();
}
return s;
}
int main()
{
BinaryTree root = CBTree();
PreOrder(root);
cout << endl;
return 0;
}