Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Tree in Javascript

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?

like image 517
Snow_Mac Avatar asked Dec 30 '25 11:12

Snow_Mac


1 Answers

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.

like image 160
Niet the Dark Absol Avatar answered Jan 01 '26 01:01

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!