Generate a node to display a complete tree with multiple children

Hello everyone!

I’d like to expand Generate coordinates for each node to display a complete binary tree? which was originally asked by @Michael_Nicol and answered by @PavelBoytchev

In my case the parent can have multiple children(more than 2) and the children always start from the left odd and right even my problem is I am having difficulties trying to adjust the code so that the parent can be shifted in the middle using the code provided in mentioned post. and the main parent should start at point (0,0).

image

Here’s the function i wrote :

var parent = {
            x: -15,
            y: 0,
            children: [],
            parent
        };
    createNode(0 , 0, parent)
    createNode(0 , 1, parent)
    createNode(1 , 1, parent)
    createNode(2 , 1, parent)
    createNode(3 , 1, parent)
  function createNode( x, y , parent = null)
  {
      var p = 2**(HEIGHT - y- 1);

      var px = 15*( p / 2 + x * p - 2**(HEIGHT-2) - 1 ),
        py = 260 - 15 * y;

        // Create the node object
        const node = {
            x: px,
            y: py,
            children: [],
            parent
        };
        
        // Add child to parent (if parent is provided)
        if (parent != null) {
            parent.children.push(node);
        }     
      
   }

Your assistance is highly appreciated.

You can just place a Group (with position shifted by 0.5) as the only child of the parent - and put actual children into that Group. Should look super clean and involves exactly 0 math :relieved:

1 Like