遍历方式(非递归),用栈,以中序遍历为例:
void InOrder_unrec(BiTree T) {
SqStack S;
InitStack(&S);
BiTree p = T;
// BiTree pop = NULL;
while (p || !IsEmpty(&S)) {
if (p) {
//栈顶元素始终是p的parent节点
Push(&S, p);
p = p->lchild;
} else {
Pop(&S, &p); //把栈顶元素弹出给p,此时变成了原p的parent
//此时p的左孩子为空,根据in-oder规则,输出根节点p,然后再以相同的方式遍历他的右孩子
printf("%c", p->data);
p = p->rchild; //输出根节点后,遍历其右子树
}
}
}
层次遍历算法
void LevelOrer(BiTree T) {
BiTree temp = NULL;
SqQueue Q;
InitQueue(&Q);
if (T) // 先入队根
EntryQ(&Q, T);
while (!IsEmpty(&Q)) {
OutQ(&Q, &temp); // temp暂存弹出值
printf("%c", temp->data); //输出
if (temp->lchild) //在入队temp的左孩子和右孩子
EntryQ(&Q, temp->lchild);
if (temp->rchild)
EntryQ(&Q, temp->rchild);
}
}
/*
input: CDNK##J##BZ###FL##M##
------------------------------------------
output:CDFNBLMKJZ
*/
建立二叉树
前+中和中+后都能确定唯一的二叉树,但是前序+后序不能,只能确定节点的父子关系。
先序遍历创建二叉树
void Creat_BiTree_Pre(BiTree *T) {
//根据输出字符识别虚空节点,'#' 代表虚空节点
char e;
scanf(" %c", &e); //输入字符
if ('#' == e)
*T = NULL; //设置虚空节点
else {
*T = (BiTree)malloc(sizeof(BiNode));
(*T)->data = e;
Creat_BiTree_Pre(&(*T)->lchild);
Creat_BiTree_Pre(&(*T)->rchild);
}
}
复制二叉树
void Copy(BiTree *Tnew, const BiTree T) {
if (!T) {
*Tnew = NULL;
return;
} else {
*Tnew = (BiTree)malloc(sizeof(BiNode));
(*Tnew)->data = T->data;
Copy(&(*Tnew)->lchild, T->lchild);
Copy(&(*Tnew)->rchild, T->rchild);
}
}
求深度和节点数
int Depth(BiTree T) {
if (!T)
return 0;
else {
return Depth(T->lchild) > Depth(T->rchild) ? Depth(T->lchild) + 1
: Depth(T->rchild) + 1;
}
}
int Nodes(BiTree T) {
if (!T)
return 0;
else
return 1 + Nodes(T->lchild) + Nodes(T->rchild);
}