求二叉树中值为x的结点的层号

题目:求二叉树中值为x的结点的层号

思路:利用访问二叉树的路径过程求解(PS:这里不是说遍历过程,是访问过程,无论前中后序遍历,访问过程都是要经过通一结点三次),利用level变量记录访问过程中的层号,递归返回要减一;

/*
求二叉树中值为x的层号

*/
#include <stdio.h>
#include <stdlib.h>

typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
    ElementType Data;
    BinTree Left;
    BinTree Right;
};

BinTree CreatBinTree(); /* 实现细节忽略 */
void level_in_x(BinTree BT,char x,int level);

int main()
{
    int level = 1;
    BinTree BT = CreatBinTree();
    level_in_x(BT,'H',level);

    return 0;
}
//静态建树
BinTree CreatBinTree()
{
    BinTree pa = (BinTree)malloc(sizeof(struct TNode));
    BinTree pb = (BinTree)malloc(sizeof(struct TNode));
    BinTree pc = (BinTree)malloc(sizeof(struct TNode));
    BinTree pd = (BinTree)malloc(sizeof(struct TNode));
    BinTree pe = (BinTree)malloc(sizeof(struct TNode));
    BinTree pf = (BinTree)malloc(sizeof(struct TNode));
    BinTree pg = (BinTree)malloc(sizeof(struct TNode));
    BinTree ph = (BinTree)malloc(sizeof(struct TNode));
    BinTree pi = (BinTree)malloc(sizeof(struct TNode));

    pa->Data = 'A';
    pb->Data = 'B';
    pc->Data = 'C';
    pd->Data = 'D';
    pe->Data = 'E';
    pf->Data = 'F';
    pg->Data = 'G';
    ph->Data = 'H';
    pi->Data = 'I';

    pa->Left = pb; pa->Right = pc;
    pb->Left = pd; pb->Right = pf;
    pc->Left = pg; pc->Right = pi;
    pd->Left = NULL; pd->Right = NULL;
    pe->Left = NULL; pe->Right = NULL;
    pf->Left = pe; pf->Right = NULL;
    pg->Left = NULL; pg->Right = ph;
    ph->Left = NULL; ph->Right = NULL;
    pi->Left = NULL; pi->Right = NULL;

    return pa;
}

void level_in_x(BinTree BT,char x,int level)
{

    if (BT == NULL){
        return ;
    }
    if(BT->Data == x){
        printf("x in %d",level);
    }
    level++;
    level_in_x(BT->Left,x,level);
    level_in_x(BT->Right,x,level);
    level--;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值