在每个结点中储存其深度。在二叉树的创建和遍历过程中可以发现,每次调用函数的时候都是前往左子树或者右子树,这个时候所前往的结点的深度都会增加一个,而当函数调用完成的时候会退出函数栈在此函数中的结点深度就会减少一个。因此可以设置一个全局变量deep来表示当前函数中的结点的深度,在创建二叉树的函数开头深度加1,当函数调用结束退栈前再将深度减1.
如下图所示的二叉树
下面是代码
#include<stdio.h>
#include<stdlib.h>
int deep=0;//在遍历树的过程中表示当前深度。
struct bitree
{
char data;
struct bitree* lchild;
struct bitree* rchild;
int deepth;
};//储存结点信息,指向左右子树的指针,以及该结点深度。
struct bitree* precreat(struct bitree* t)
{
char ch;
scanf("%c",&ch);
deep++;//每次调用函数深度+1.
if(ch==' ')t=NULL;
else
{
if(!(t=(struct bitree*)malloc(sizeof(struct bitree))))exit(0);
t->data=ch;
t->lchild=precreat(t->lchild);
t->rchild=precreat(t->rchild);
t->deepth=deep;