我創建了一個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()內部,但在打印返回的指針時不行。我究竟做錯了什麼?
注意:在'int l = i-pow(2,h-1)'中使用FP數學是弱編程。推薦用整數數學計算2的冪。 – chux
@chux你是什麼意思?我該怎麼做?這是一個演員(int)好嗎? –
看到http://stackoverflow.com/questions/12556906/are-2n-exponent-calculations-really-less-efficient-than-bit-shifts和 – chux