求二叉树最浅叶子结点们的和

这篇博客探讨了如何利用图的宽度优先遍历(BFS)算法,解决求解二叉树中最浅叶子节点之和的问题。通过对二叉树进行层次遍历,可以有效地找到距离根节点最近的叶子节点,并累加它们的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <malloc.h>

#define maxlen 30

typedef struct Node
{
    struct Node * leftChild;
    struct Node * rightChild;
    int key;
}Node;

Node *initTree()
{
    int n = 0;
    scanf("%d",&n);
    if(0 == n){
        return NULL;
    }
    Node *p = (Node *)malloc(sizeof(Node));
    p->key = n;
    p->leftChild = initTree();
    p->rightChild = initTree();

    return p;
}

void preOrderRecursive(Node *root)
{
    if(root){
        printf("%d\n",root->key);
        preOrderRecursive(root->leftChild);
        preOrderRecursive(root->rightChild);
    }
}

int getResult(Node *pTree)
{
    Node *queue[maxlen];
    int front = 0;
    int rear = 0;

    int count = 0;

    queue[(++rear)%maxlen] = pTree;
    int last = 1;
    while(front != rear){
        Node *tmp = queue[(++front)%maxlen];

        if(tmp->leftChild == NULL && tm
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值