riquito / Baobab

A library applying the nested set model
http://baobab.sideralis.org
Apache License 2.0
90 stars 27 forks source link

How can we find the parent's last child? #17

Closed beshoo closed 2 years ago

beshoo commented 2 years ago

Thank you for the Baobab lib, it is very useful. Well, I have a question.

I created a binary tree with the nested set module. but am struggling to find the parent's most left or right node.

Since the getLastChild returns the first child. not the last node in the tree. So how can we find the parent's last child?

Please advice. image

riquito commented 2 years ago

Hi, it's been a long time since I looked at Baobab, so forgive me for any imprecision. The tree built in a nested set model is not a binary tree. Every node can have 1 to N children, so children are not really split between left and right. Your red "left most" node is not left most at all, it's not left or right of its child (or left or right of its parent), so it's not special in any way.

Here's your tree using some labels (easier to talk about, using mermaid syntax in markdown)

graph TD;
    A-->B;
    A-->C;
    B-->D;;
    B-->E;
    D-->G;
    G-->L;
    C-->F;
    F-->H;
    F-->I;
    H-->M;
    I-->N;
    N-->O;

If I were to search for leftmost and rightmost, I'd say they are L and O. You can find them using getLeaves(), then in the resulting array they will be the first one (L) and the last one O

beshoo commented 2 years ago

Thank you for your kindly reply I do understand that the nested set lft and rgt are not RIGHT LEFT of the node. for that reason, am only add 2 children for the node, and to mark if this child is on the left or right side of the node to create binary tree, I created another field named a position which I will mark the node if it is On The LEFT or Right, and when I want to insert a new node I will give it this mark.

Noe let's assume the "L" has a new child on the RIGHT. So L will not be Leave but the "LEFT" as a binary is empty. So how can i get if the node is Leave or it has one child?

riquito commented 2 years ago

Uh, that's quite special, let's see. In your tree, every parent of a single leaf have rgt - lft == 3, so you could search for them using a SQL query and then see if their only child is left or right. This is not fast but it's not terrible either (you have to investigate only children of single parents)

beshoo commented 2 years ago

Thank you , problem solved