简体   繁体   English

C-二进制树:无法返回正确数目的修剪节点

[英]C - binary tree: can't return correct number of pruned nodes

I need to prune a binary tree past a certain level, l and need to return the number of pruned nodes. 我需要修剪超过一定级别l的二叉树,并且需要返回修剪的节点数。

Here's what I got: 这是我得到的:

#include "abin.h"

int freeAB (ABin a) {
    int count = 0;
    if(a == NULL) return count;
    count = count + freeAB(a->esq);
    count = count + freeAB(a->dir);
    free(a);
    count++;
    return count;
}


int pruneAB (ABin *a, int l) {

    int count = 0;
    if(l == 0){
        count = count + freeAB((*a)->esq);
        count = count + freeAB((*a)->dir);
        (*a) = NULL;
    }
    else{
        count = count + pruneAB(&((*a)->esq), l-1);
        count = count + pruneAB(&((*a)->dir), l-1);
    }
    return count;
 }

ABIN.H: ABIN.H:

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

typedef struct lligada {
    int valor;
    struct lligada *prox;
} *LInt;

typedef struct nodo {
    int valor;
    struct nodo *esq, *dir;
} *ABin;

int pruneAB (ABin *a, int l);     

This is the output of what I should have got and what I got: 这是我应该得到和得到的结果的输出:

Input: (depth=2)
               8
       4              12
   2       6      10      14
 1   3   5   7   9  11  13  15

Output:
[expected] res=12
   8
 4  12

[obtained] res=8
   8
 4  12

0/10 correct answers

Interestingly, if I create something like int r = 0; 有趣的是,如果我创建类似int r = 0的东西; and do r++; 并做r ++; every time the if(l == 0) statement is true, and then do a print statement, it prints r 4 times. 每当if(l == 0)语句为true,然后执行print语句时,它将打印r 4次。

If I added 4 to the final count I would get the correct answer. 如果我在最终计数中加4,我会得到正确的答案。 I assume that I should then add to count the number of times the if(l == 0) is true. 我假设我应该加法计算if(l == 0)为真的次数。

(I can't do it. If I do count++ I get segmentation fault) (我做不到。如果我计算++,我会遇到细分错误)

How would you do it? 你会怎么做? Thanks. 谢谢。

https://codeboard.io/projects/16275 https://codeboard.io/projects/16275

int pruneAB (ABin *a, int l) {
    int count = 0;
    if (!*a) return 0;
    if (l < 0) return count;
    if(l == 0){
        count = freeAB(*a);
        (*a) = NULL;
    }
    else{
        count = count + pruneAB(&((*a)->esq), l-1);
        count = count + pruneAB(&((*a)->dir), l-1);
    }
    return count;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM