二叉链表结构:
typedef int datatype;
struct bnodepe
{
datatype data;
struct bnodepe *lchild, *rchild;
};
typedef struct bnodept *bitreptr;
三种遍历
(1)先序
void preorder(bitreptr t)
{
if (t)
{
visit(t->data);
preorder(t->lchild);
preorder(t->rchild);
}
}
(2)中序
void inorder(bitreptr t)
{
if (t)
{
inorder(t->lchild);
visit(t->data);
inorder(t->rchild);
}
}
(3)后序
void postorder(bitreptr t)
{
if (t)
{
postorder(t->lchild);
posyorder(t->rchild);
visit(t->data);
}
}
先序非递归算法:
void preorder(bitreptr t)
{
bitreptr stack[MAX + 1]; //顺序栈
int top = 0; //栈顶指针
do
{
while (t)
{
visit(t->data); //访问根结点
if (top == MAX)
{
printf("stack full");
return;
}
stack[++top] = t;
t=t->lchild;
}
if (top != 0) //如果栈中还有跟指针
{
t = stack[top--]; //取出跟指针
t = t->rchild; //移向右子树
}
} while (top!=0||t!=NULL) //栈非空或非空子树
}
求二叉树以值为x的结点为根的子树的深度:
int Get_Depth(bitreptr T)
{
int m, n;
if (!T)
return 0;
else
{
m = Get_Depth(T->lchild);
n = Get_Depth(T->rchild);
return (m > n ? m : n) + 1;
}
}
int preorder_ch(bitreptr root, datatype ch)
{
int lev, m, n;
if (root == NULL)
lev = 0; //空树
else if (root->data == ch)
lev = 1; //ch所在结点为根结点
else
{
m = preorder_ch(root->lchild, ch); //左子树查找
n = preorder_ch(root->rchild, ch);
if (m == 0 && n == 0)
lev = 0; //查找失败
else
lev = ((m > n) ? m : n) + 1;//查找成功,层数加1
}
return lev;
}
按先序建立二叉树的二叉链表:
bitreptr crt_bt_pre()
{
char ch;
bitreptr bt;
ch = getchar();
if (ch == ' ')
return NULL;
else
{
bt = (bitreptr)malloc(sizeof(struct bnodept));//产生新结点
bt->data = ch;
bt->lchild = crt_bt_pre();
bt->rchild = crt_bt_pre();
return bt;
}
}
求二叉树的叶子树:
int countleaf(bitreptr root)
{
int i;
if (root == NULL)
i = 0;
else if ((root->lchild == NULL) && (root->rchild == NULL))
i = 1;
else
{
i = countleaf(root->lchild) + countleaf(root->rchild);
}
return i;
}