二叉树常用存储结构,采用链表:
struct node
{
int value;
node *leftchild, *rightchild;
//int id; // 结点编号。
//node *parent; // 指向父亲结点。
} arr[N];
int top=-1;
node * head = NULL;
#define NEW(p) p=&arr[++top]; p->leftchild=NULL;
p->rightchild=NULL; p->value=0
有宏定义的时候,记得换行时使用“”符号。
三种遍历实现代码如下:
1. 前序遍历
void preorder(node *p)
{
if (p==NULL) return;
// 处理结点p
cout<<p->value<<' ';
preorder(p->leftchild);
preorder(p->rightchild);
}
2. 中序遍历
void inorder(node *p)
{
if (p==NULL) return;
inorder(p->leftchild);
// 处理结点p
cout<<p->value<<' ';
inorder(p->rightchild);
}
3. 后序遍历
void postorder(node *p)
{
if (p==NULL) return;
postorder(p->leftchild);
postorder(p->rightchild);
// 处理结点p
cout<<p->value<<' ';
}