title: How to create binary tree in parse cloud code
body: <p>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.</p>
  
  <p>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.</p>
  
  <p><strong>Save Bracket Function</strong></p>
  
  <pre><code>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);
      }
  });
  </code></pre>
  
  <p><strong>Create Bracket Function</strong></p>
  
  <pre><code>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 &lt; extraLayerCount; i++)
      {
          console.log("Adding layer " + i);
          addLayer(bracket);
      }
  
      return bracket;
  }
  </code></pre>
  
  <p><strong>Add Layer Function</strong></p>
  
  <pre><code>function addLayer(match)
  {
      leftChild = match.get('leftChild');
      rightChild = match.get('rightChild');
  
      console.log("Checking if match has children");
      if (leftChild != null &amp;&amp; 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);
      }
  }
  </code></pre>