二叉树数叶子,计算树高

int CountLeaf(BiTree T){
    if(T == NULL) return 0;
    if(T->lchild == NULL && T->rchild == NULL)
        return 1;
    else{
        n1 = CountLeaf(T->lchild);
        n2 = CountLeaf(T->rchild);
        return n1+n2;
        }
    }
void BiTreeDepth(BiTree T,int level,int& depth){
    if(T){
        if(level > depth) depth = level;
        BiTreeDepth(T->Lchild,level+1,depth);
        BiTreeDepth(T->Rchild,level+1,depth);
        }
    }
### 计算二叉树叶子节点个的算法 #### 方法一:递归实现 通过递归的方式可以方便地计算二叉树中的叶子节点量。对于每一个节点,如果其左子树和右子树都为空,则说明这是一个叶子节点[^2]。 以下是基于递归方法的代码实现: ```c typedef struct BiTNode { char data; struct BiTNode* lchild, *rchild; } BiTNode, *BiTree; int countLeafNodesRecursively(BiTree T) { if (T == NULL) { // 如果当前节点为空,返回0 return 0; } if (T->lchild == NULL && T->rchild == NULL) { // 判断是否为叶子节点 return 1; } // 对左右子树分别递归调用并累加结果 return countLeafNodesRecursively(T->lchild) + countLeafNodesRecursively(T->rchild); } ``` 此函的核心逻辑在于判断当前节点是否满足叶子节点的条件(即 `lchild` 和 `rchild` 均为 `NULL`),如果是则计器增加;如果不是,则继续对左右子树进行递归操作[^2]。 --- #### 方法二:非递归实现(层次遍历) 另一种常见的方法是非递归方式,通常借助队列来完成层次遍历。这种方法适合于大规模据集或者为了避免栈溢出的情况[^1]。 以下是基于非递归方法的代码实现: ```c #include <stdio.h> #include <stdlib.h> // 定义二叉树节点结构 typedef struct BiTNode { char data; struct BiTNode* lchild, *rchild; } BiTNode, *BiTree; // 定义队列节点结构 typedef struct QueueNode { BiTree tree; struct QueueNode* next; } QueueNode; // 创建新队列节点 QueueNode* createQueueNode(BiTree tree) { QueueNode* newNode = (QueueNode*)malloc(sizeof(QueueNode)); newNode->tree = tree; newNode->next = NULL; return newNode; } // 层次遍历统计叶子节点目 int countLeafNodesIteratively(BiTree root) { if (root == NULL) { return 0; } int leafCount = 0; QueueNode* front = NULL, *rear = NULL; // 初始化队列 rear = createQueueNode(root); front = rear; while (front != NULL) { BiTree current = front->tree; // 若当前节点为叶子节点,计器加1 if (current->lchild == NULL && current->rchild == NULL) { leafCount++; } // 将左右子节点入队 if (current->lchild != NULL) { rear->next = createQueueNode(current->lchild); rear = rear->next; } if (current->rchild != NULL) { rear->next = createQueueNode(current->rchild); rear = rear->next; } // 移动到下一个队列节点 QueueNode* temp = front; front = front->next; free(temp); // 释放已处理的队列节点内存 } return leafCount; } ``` 在此实现中,使用了一个辅助的据结构——队列,用于存储待处理的节点。每次从队列头部取出一个节点,检查它是否为叶子节点,并将其子节点加入队列中等待后续处理。 --- ### 性能分析 - **时间复杂度**:无论是递归还是迭代方法,都需要访问每个节点一次,因此时间复杂度均为 O(n),其中 n 是二叉树中节点的量。 - **空间复杂度**: - 递归方法的空间复杂度取决于递归的最大深度,在最坏情况下可能达到 O(h),h 表示树的高度。 - 迭代方法的空间复杂度主要由队列决定,最大可能占用 O(w),w 表示树中最宽的一层所含有的节点[^1]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值