二叉树的层数、高度和子孙遍历

层数遍历:

typedef struct Snode
{
    int data;
    int layer;                  //layer表示节点的层数
    struct Snode * Lson,* Rson; //节点的左右儿子
}Snode,*ptr;

void level(ptr p,int i)
{
    if(p==NULL) return;         //结束标志
    p->layer=i;                 //填写层数
    printf("%d %d",p->data,p->layer);//输出层数
    level(p->Lson,i+1);          //递归输出子孙层数
    level(p->Rson,i+1);
}

高度遍历:

typedef struct Snode
{
    int data;
    int height;                  //height表示节点的高度
    struct Snode * Lson,* Rson; //节点的左右儿子
}Snode,*ptr;

int Height(ptr p)
{
    int i,j;
    if(p==NULL) return 0;               //结束标志
    i=Height(p->Lson);                  //得到左儿子的高度
    j=Height(p->Rson);                  //得到右儿子的高度
    p->height=(i>j)?i+1:j+1;            //自身的高度等于儿子中最大高度+1
    printf("%d %d",p->data,p->height);  //输出节点及高度
    return p->height;                      //返回自身高度
}

输出所有子孙:

typedef struct Snode
{
    int data;
    struct Snode * Lson,* Rson; //节点的左右儿子
}Snode,*ptr;

void descents(ptr p,int x)
{
    if (p==NULL||found==3) {
        return;                 //NULL表示找到头了,found=3表示节点子孙访问完毕,返回根节点了
    }
    if (p->data==x) {           //第一次找元素x标记
        found=1;
    }
    if (found=1) {              //由于第一次找到了,所以接下来的递归调用found都
        printf("%d",p->data);
    }
    descents(p->Lson, x);
    descents(p->Rson, x);
    if(p->data==x) found=3;
}

猜你喜欢

转载自blog.csdn.net/qq_41995348/article/details/80609597
今日推荐