3

I'm working on this assignment: http://www.cs.colostate.edu/~anderson/ct310/index.html/doku.php?id=assignments:assignment_2

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 & right child are just new tree objects stored in var.

Here's the tree class:

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

}

Here's the toString() method

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

Here's the data I get passed into. We're using Rhino in the command line to test.

var abc = new Tree('a', new Tree('b'), new Tree('c'));
abc.toString()

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.

Any ideas what's wrong?

2
  • did you mean: if(this.left()) -- without the this.tree()? There is no this.tree in the constructor :) Commented Feb 17, 2012 at 15:37
  • It's strange to me to call this class "tree" instead of "node" as tree is the name of the larger structure. I would call a structure composed of trees with two pointers a binary forest. ba-bum-ch. Commented Feb 17, 2012 at 15:49

2 Answers 2

3

Well, your last reference to the right branch is missing some parentheses...

this.tree.right().toString(indent+5) // <-- right here

That asid, I don't see this.tree() defined anywhere. I think it should be this.left() and this.right() in all those places.

Also, for a slight optimisation, consider something like:

var l = this.left();
if( l) l.toString(indent+5);

This avoids an extra function call.

Sign up to request clarification or add additional context in comments.

Comments

1

Your recursive function has no base case. It will just keep going forever.

If your node doesn't have any children, than don't call ToString on them()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.