I have several binary trees stored in an array. In each slot, either nil (or null, select your language), or a fixed tuple that stores two numbers: the indices of two "children". No node will have only one child - it is either not or two.
Think of each slot as a binary node that stores pointers only for its children and has no built-in value.
Take this binary tree system:
0 1
/ \ / \
2 3 4 5
/ \ / \
6 7 8 9
/ \
10 11
Associated Array:
0 1 2 3 4 5 6 7 8 9 10 11
[ [2,3] , [4,5] , [6,7] , nil , nil , [8,9] , nil , [10,11] , nil , nil , nil , nil ]
I already wrote simple functions for finding direct parents of nodes (just by searching from the front until there is a node that contains a child)
, , .
P(m,n)
m n - , LCA " " node, m n ( , ..). , nil .
, :
P( 6,11)
P( 3,10)
P( 8, 6)
P( 2,11)
, , , , ( node A 0 1 "" -1), :
A-0-2-6-2-7-10-7-11-7-2-0-3-0-A-1-4-1-5-8-5-9-5-1-A
node m n, ; , P (6,11), 6 11 . , , 2, . A (-1) , nil.
-- Calculating P(6,11) --
A-0-2-6-2-7-10-7-11-7-2-0-3-0-A-1-4-1-5-8-5-9-5-1-A
^ ^ ^
| | |
m lowest n
, , , , - ... , , , LCA, .
, , ? , , , ? , , - "" / node, , - .
, , , 3025, 0, , , , , , .
?
, , .
, n X, (X-1) , n. :
0
/ \
/ \
/ \
1 2 6
/ \ / \ / \
2 3 9 10 7 8
/ \ / \
4 5 11 12
- .
, , .