Search code examples
recursionparse-platformtreesaveparse-cloud-code

How to create binary tree in parse cloud code


I need to create a tournament bracket in parse cloud code, however I am unable to do this since you cannot create a pointer to an unsaved object.

How am I supposed to go about initializing a tree like object with this constraint? I can't save each bracket as I loop through since the save function is asynchronous.

Save Bracket Function

console.log('create bracket / end qualifier');
tournament.save('bracket', createBracket(tournament.get('players')),
{
    success: function(result)
    {
        console.log("saved!");
        callback(result);
    },
    error: function(result, error)
    {
        console.log("failed!");
        console.log(error.message);
        callback(result);
    }
});

Create Bracket Function

function createBracket(players)
{
    console.log("Creating bracket");
    var bracket = new Parse.Object("Match");
    bracket.set('matchId', 1);

    var extraLayerCount = getLayerCount(players);

    for (var i = 0; i < extraLayerCount; i++)
    {
        console.log("Adding layer " + i);
        addLayer(bracket);
    }

    return bracket;
}

Add Layer Function

function addLayer(match)
{
    leftChild = match.get('leftChild');
    rightChild = match.get('rightChild');

    console.log("Checking if match has children");
    if (leftChild != null && rightChild != null)
    {
        console.log("Has children, telling children to add layers");
        addLayer(leftChild);
        addLayer(rightChild);
    }
    else
    {
        console.log("Creating new children");
        var leftChild = new Parse.Object("Match");
        leftChild.set('matchId', match.get('matchId') * 2);
        match.set('leftChild', leftChild);

        var rightChild = new Parse.Object("Match");
        rightChild.set('matchId', match.get('matchId') * 2 + 1);
        match.set('rightChild', rightChild);
    }
}

Solution

  • My solution to this was to create it from the bottom up, so instead of:

              1
        2           3
    4       5   6       7
    

    It was

              7
        5           6
    1       2   3       4
    

    So I create each match in the bottom layer, then when they finish saving, create parents for each pair, save those, and continue doing that until there is 1 left, which I return as the first match of the tree :)