A binary tree is represented in an array as follows: [father, left son, right son, ...]. More precisely, the father’s Dice is worth (i - 1) / 2
, left son’s 2*i + 1
and that of law 2*i + 2
.
Implementation Quick and Dirty, assuming an AB (not ABP) of numbers:
/* Retorna o indice do nodo na arvore, ou UINT_MAX se nao encontrado -- O(n) */
size_t
index(int *tree, size_t nmemb, int node)
{
size_t i = 0;
while (i < nmemb && tree[i] != node)
++i;
return i < nmemb ? i : -1;
}
int
parent(int *tree, size_t nmemb, int node)
{
size_t i = index(tree, nmemb, node);
if (i >= nmemb || !i)
return INT_MAX;
return tree[(i - 1) / 2];
}
int
left(int *tree, size_t nmemb, int node)
{
size_t i = index(tree, nmemb, node);
size_t ans = 2*i + 1;
if (i >= nmemb || ans >= nmemb)
return INT_MAX;
return tree[ans];
}
int
right(int *tree, size_t nmemb, int node)
{
size_t i = index(tree, nmemb, node);
size_t ans = 2*i + 2;
if (i >= nmemb || ans >= nmemb)
return INT_MAX;
return tree[ans];
}
E.g. http://pastebin.com/iGkk0UPq
debian@pc:~ ./a.out 2
Pai de 1: 2147483647 Esquerda: 2 Direita: 2147483647
Pai de 2: 1 Esquerda: 2147483647 Direita: 2147483647
debian@pc:~ ./a.out 3
Pai de 1: 2147483647 Esquerda: 2 Direita: 3
Pai de 2: 1 Esquerda: 2147483647 Direita: 2147483647
debian@pc:~ ./a.out 4
Pai de 1: 2147483647 Esquerda: 2 Direita: 3
Pai de 2: 1 Esquerda: 4 Direita: 2147483647
debian@pc:~ ./a.out 5
Pai de 1: 2147483647 Esquerda: 2 Direita: 3
Pai de 2: 1 Esquerda: 4 Direita: 5
You have here an implementation of a binary tree: https://msdn.microsoft.com/en-us/library/ms379572%28v=vs.80%29.aspx
– bruno
A binary tree is represented in an array as follows: [father, left son, right son, ...]. More precisely, the father’s Dice is worth
(i - 1) / 2
, left son’s2*i + 1
and that of law2*i + 2
.– Alex
Similar to what you need: http://www.introprogramming.info/tag/binary-search-trees/
– Felipe Douradinho
@Alex, how I would represent the posted image, in an array as you are placing it. I still can’t implement.
– pnet
pnet, managed to reach a solution, put there if possible ..
– user27534
Not yet. I’m reading a lot on the subject.,
– pnet