二叉树的操作

时间:2021-04-11 17:31:46

二叉树的简单操作:

struct node
{
int val;
node *ch[2]; //ch[0]代表左孩子,ch[1]代表右孩子
};

int Height(node *t) //计算二叉树的高度
{
int ldep,rdep;
if (t==NULL)
return 0;
else
{
ldep=Height(t->ch[0]);
rdep=Height(t->ch[1]);
return (ldep>rdep) ? (ldep+1):(rdep+1);
}
}

int NodeCount(node *t) //统计节点个数
{
if (t==NULL) return 0;
else return NodeCount(t->ch[0]) + NodeCount(t->ch[1]) + 1;
}

int LeafCount(node *t) //统计叶子节点个数
{
if (t==NULL) return 0;
else if(t->ch[0]==NULL && t->ch[1]==NULL)
return 1;
else LeafCount(t->ch[0]) + LeafCount(t->ch[1]);
}

void Print(node *t) //二叉树的广义表形式输出
{
if(t!=NULL)
{
printf("%d",t->val);
if(t->ch[0]!=NULL||t->ch[1]!=NULL)
{
printf("(");
Print(t->ch[0]);
if(t->ch[1]!=NULL)
printf(",");
Print(t->ch[1]);
printf(")");
}
}
}

void Preorder(node *t) //前序遍历
{
if(t!=NULL)
{
printf("%d ",t->val);
Preorder(t->ch[0]);
Preorder(t->ch[1]);
}
}

void Inorder(node *t) //中序遍历
{
if(t!=NULL)
{
Inorder(t->ch[0]);
printf("%d ",t->val);
Inorder(t->ch[1]);
}
}

void Postorder(node *t) //后序遍历
{
if(t!=NULL)
{
Postorder(t->ch[0]);
Postorder(t->ch[1]);
printf("%3c",t->val);
}
}

void LevelOrder(node *t) //层序遍历
{
if(t==NULL) return;
node *Q[N];
int front = -1,rear = 0;
Q[rear]=t;
while(front!=rear)
{
front++;
printf("%d ",Q[front]->val);
if(Q[front]->ch[0]!=NULL)
{
rear++;
Q[rear]=Q[front]->ch[0];
}
if(Q[front]->ch[1]!=NULL)
{
rear++;
Q[rear]=Q[front]->ch[1];
}
}
}