查找根与二叉树中任何节点之间的距离

时间:2014-10-15 09:40:19

标签: c binary-tree

我正在尝试编写一个代码来查找根和二叉树中任何节点之间的距离。如果我要查找的节点的值不在树中,我将其添加到树中并写入其深度。我试着编写一个代码但不知何故为root我得到正确的答案(深度= 0)和其他任何东西我得到深度= 1的值。我一直在寻找代码已经有一段时间了,所以也许你们可以提供帮助。非常感激。

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

typedef struct b_tree t;

struct b_tree {
    int value;
    struct b_tree * right;
    struct b_tree * left;
};


int add(t **root, t *bam, int pom) {

    if ((*root) == NULL) {
        *root = bam;
        return pom;
    }
    else {
        if((*root)->value == bam->value){
            return pom;
        }
        else if((*root)->value > bam->value) {
            pom++;
            add(&(*root)->left, bam, pom);
        }

        else if ((*root)->value < bam->value) {
            pom++;
            add(&(*root)->right, bam, pom);
        }




    }

    return pom;
}



int main() {
    t *akt, *root = NULL;
    int x=1, pom=0, depth;

    while (x!=0){

        scanf("%d", &x);
        pom=0;
        akt = (t *)malloc(sizeof(t));
        akt->left = akt->right = NULL;
        akt->value = x;
        depth = add(&root, akt, pom);
        printf("%d\n", depth);

    }

    return 0;
}

调试时,代码进入一个不寻常的循环(??)。如果pom是从根到节点表示为我的深度的值,它的作用是,它得到正确答案(节点深度为3,pom = 3),但是当我尝试返回pom时;由于未知原因(对我而言)pom总是降低到1.感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您正在放弃对add()的递归调用返回的值。将呼叫更改为:

return add(&(*root)->left, bam, pom);
...
return add(&(*root)->right, bam, pom);
相关问题