title: Binary Tree in Javascript
body: <p>I'm working on this assignment: <a href="http://www.cs.colostate.edu/~anderson/ct310/index.html/doku.php?id=assignments:assignment_2" rel="nofollow">http://www.cs.colostate.edu/~anderson/ct310/index.html/doku.php?id=assignments:assignment_2</a></p>
  
  <p>I'm building a binary tree in Javascript. Basically it's a relational tree, we have this tree class that takes 3 arguments: data,left child,right child. Left &amp; right child are just new tree objects stored in var. </p>
  
  <p>Here's the tree class:</p>
  
  <pre><code>function Tree( data, left, right ) 
  {   
      // pravite data 
      var data = data; 
      var leftChild = left; 
      var rightChild = right; 
  
      // public functions 
      this.getData = function()
      {
          return data;
      }
  
      this.left = function()
      {
          return leftChild; 
      }
  
      this.right = function()
      {
          return rightChild; 
      }
  
  }
  </code></pre>
  
  <p>Here's the toString() method</p>
  
  <pre><code>Tree.prototype.toString = function(indent) 
  {
    var spaces = '';
    if (!indent)
    {
      indent = 0;
    }
    else{
      spaces = spaces*indent; 
    }
      // if the left tree isn't void
      if(this.tree().left())
      {
          this.tree().left().toString(indent+5); 
      }
      if(this.tree().right())
      {
          this.tree.right().toString(indent+5); 
      }
      print(spaces + this.data);
  }
  </code></pre>
  
  <p>Here's the data I get passed into. We're using Rhino in the command line to test. </p>
  
  <pre><code>var abc = new Tree('a', new Tree('b'), new Tree('c'));
  abc.toString()
  </code></pre>
  
  <p>I get a stack over flow on the toString method. My professor says to use the this.Left() in the if statement because when you recurse it will fail when it's undefined. </p>
  
  <p>Any ideas what's wrong? </p>