私はバイナリ検索ツリーのようにインデックスを使用する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);
}
}
}
私は実行私の本(root->左>左はノードインデックス#2がある)のようなメイン:
DIRECをpritingときに私は両方の右のポインタを取得する理由2 0x7ffd1dd011a0
Found 0x7ffd1dd011a0
0x0
私は理解していない:
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);
は、私は次の出力を得ます私は戻ってきたポインタを印刷するときにはget_node_mt()関数の中でroot-> left-> leftを使用しています。私は間違って何をしていますか?
注: '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