2016-03-17 84 views
0

我需要在解析雲代碼時創建錦標賽括號,但是我無法做到這一點,因爲您無法創建指向未保存對象的指針。如何在解析雲代碼中創建二叉樹

我該如何去初始化像這樣的約束對象樹?由於save函數是異步的,因此我無法保存每個括號。

保存包圍式曝光功能

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

回答

0

我對這個解決方案是從下往上創建它,所以不是:

  1 
    2   3 
4  5 6  7 

這是

  7 
    5   6 
1  2 3  4 

所以我創造每場比賽在底層,然後當他們完成節能,爲每一對創建父母,保存這些,並繼續這樣做,直到剩下1個,我將作爲樹的第一個匹配返回:)