如何在解析云代码中创建二叉树



我需要在解析云代码中创建一个锦标赛支架,但是我无法执行此操作,因为您无法创建指向未保存对象的指针。

我应该如何使用此约束初始化树状对象?我无法在循环时保存每个括号,因为保存函数是异步的。

保存支架功能

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);
    }
});

创建括号函数

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;
}

添加图层函数

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);
    }
}

我的解决方案是自下而上地创建它,而不是:

          1
    2           3
4       5   6       7

它是

          7
    5           6
1       2   3       4

所以我在底层创建每个匹配项,然后当他们完成保存时,为每对创建父项,保存这些项,并继续这样做,直到剩下 1 个,我将其作为树的第一个匹配项返回:)

最新更新