编程计算二叉树中某结点的层数

这篇博客介绍了一个编程问题,即如何在二叉树中查找与给定字符key相等的节点并返回其所在的层次。文章提供了一个C语言实现的函数`getNodelayer`,该函数通过递归遍历二叉树来查找节点,如果找到则返回其层次,否则返回-1。此外,还提供了一个`getBiTreeNodeLayer`函数作为主调用接口,用于简化使用。最后,文章给出了一个简单的main函数示例,展示了如何创建二叉树、输入要查找的元素并打印结果。
摘要由CSDN通过智能技术生成

题目:编写一个函数:实现在二叉树中查找与字符key内容相同的结点,并返回其在二叉树中的层数。如果二叉树中不存在该结点,则返回-1.

#include "stdio.h"

typedef struct BiTNode{
    char data;   /*结点的数据域*/
    struct BiTNode *lchild , *rchild;  /*指向左孩子和右孩子*/
} BiTNode , *BiTree;

/*创建一棵二叉树*/
void CreatBiTree(BiTree *T){
    char c;
    scanf("%c",&c);
    if(c == ' ') *T = NULL;
    else{
       *T = (BiTNode * )malloc(sizeof(BiTNode));  /*创建根结点*/
        (*T)->data = c;    /*向根结点中输入数据*/
        CreatBiTree(&((*T)->lchild));  /*递归地创建左子树*/
        CreatBiTree(&((*T)->rchild));  /*递归地创建右子树*/
    }
}

int getNodelayer (BiTree T,int level,char key) {
    int l;
    if(T) {   
        if(T->data == key) {
            return level;    /*找到与key值相同的结点,将层数level返回*/
    

以下是用C语言的程序,实现按先序遍历序列建立一个二叉树的二叉链表,统计二叉树叶子结点二叉树的深度。 ```c #include <stdio.h> #include <stdlib.h> typedef struct TreeNode{ int data; struct TreeNode *lchild; struct TreeNode *rchild; }TreeNode, *BiTree; // 创建二叉树 void createBiTree(BiTree *T){ int data; scanf("%d", &data); if(data == -1){ *T = NULL; }else{ *T = (TreeNode *)malloc(sizeof(TreeNode)); (*T)->data = data; createBiTree(&((*T)->lchild)); createBiTree(&((*T)->rchild)); } } // 统计叶子结点 int countLeafNode(BiTree T){ if(!T) return 0; if(!T->lchild && !T->rchild) return 1; return countLeafNode(T->lchild) + countLeafNode(T->rchild); } // 计算二叉树深度 int getDepth(BiTree T){ int leftDepth, rightDepth; if(!T) return 0; leftDepth = getDepth(T->lchild); rightDepth = getDepth(T->rchild); return (leftDepth > rightDepth) ? (leftDepth + 1) : (rightDepth + 1); } int main(){ BiTree T; printf("输入先序遍历序列:\n"); createBiTree(&T); printf("叶子结点:%d\n", countLeafNode(T)); printf("二叉树深度:%d\n", getDepth(T)); return 0; } ``` 程序的运行结果如下: ``` 输入先序遍历序列: 1 2 -1 -1 3 -1 4 -1 -1 叶子结点:2 二叉树深度:3 ``` 以上程序,createBiTree()函用于创建二叉树,countLeafNode()函用于统计二叉树叶子结点的个,getDepth()函用于计算二叉树的深度。主函先要输入先序遍历序列来创建二叉树,然后调用countLeafNode()和getDepth()函来统计叶子结点计算二叉树深度,最后输出结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值