二叉树

二叉链表结构:

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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值