2016-11-04 99 views
0

我創建了一個C中的二叉樹,其中我使用二叉搜索樹中的索引。我在找到節點的函數時遇到問題。函數獲取正確的指針,但返回NULL

我對樹的代碼是在一個單獨的文件,它的下面:

struct node { 
    struct node *left; 
    struct node *right; 
    int index; 
    void *data; 
}; 

struct node * init_mt() 
{ 
    struct node *root = malloc(sizeof(struct node)); 
    root->index = -1; 
    root->data = NULL; 
    root->left = root->right = NULL; 
    return root; 
} 

void create_mt(struct node *mt, int h, int i) 
{ 
    if (h == 0) // end of tree reached 
    { 
    mt->index = 0; 
    mt->left = mt->right = NULL; 
    return; 
    } 
    else 
    { 
    mt->index = i; 
    int l = i-pow(2,h-1); 
    int r = i+pow(2,h-1); 
    mt->left = malloc(sizeof(struct node)); 
    mt->right = malloc(sizeof(struct node)); 
    create_mt(mt->left,h-1,l); 
    create_mt(mt->right,h-1,r); 
    } 
} 

struct node * get_node_mt(struct node *mt, int p, int h) 
{ 
    if (h == -1) // end of tree reached 
    { 
    return NULL; 
    } 
    else 
    { 
    if (mt->index == p) 
    { 
     printf("Found %p\n", mt); 
     return mt; 
    } 
    else if (mt->index > p) 
    { 
     get_node_mt(mt->left,p,h-1); 
    } 
    else 
    { 
     get_node_mt(mt->right,p,h-1); 
    } 
    } 
} 

當我跑我的主要是這樣的(根 - >左>左爲節點索引#2):

struct node *root = NULL; 
root = init_mt(); 
create_mt(root,3,8); // root index == 8 
printf("%d %p\n", root->left->left->index,root->left->left); 
struct node *find; 
find = get_node_mt(root,2,3); 
printf("%p\n", find); 

我得到以下輸出:

2 0x7ffd1dd011a0 
Found 0x7ffd1dd011a0 
0x0 

我不明白爲什麼我得到正確的指針都priting直銷時tly使用root-> left-> left並在函數get_node_mt()內部,但在打印返回的指針時不行。我究竟做錯了什麼?

+0

注意:在'int l = i-pow(2,h-1)'中使用FP數學是弱編程。推薦用整數數學計算2的冪。 – chux

+0

@chux你是什麼意思?我該怎麼做?這是一個演員(int)好嗎? –

+0

看到http://stackoverflow.com/questions/12556906/are-2n-exponent-calculations-really-less-efficient-than-bit-shifts和 – chux

回答

3

get_node_mt()函數在兩處調用自己。這兩個地方都沒有返回價值。

struct node * get_node_mt(struct node *mt, int p, int h) 
{ 
    if (h == -1) // end of tree reached 
     return NULL; 
    else if (mt->index == p) 
     return mt; 
    else if (mt->index > p) 
     get_node_mt(mt->left,p,h-1); 
    else 
     get_node_mt(mt->right,p,h-1); 
} 

我重新格式化了代碼,刪除了很多大括號。編譯器應該已經警告過這個問題,恕我直言。

+0

我仍然得到一個NULL指針。 –

+0

您是否添加了返回語句? –

+0

哦,不!對。抱歉。現在它工作了!謝謝! –