2
\$\begingroup\$

I wrote a basic binary tree in JS. Can anyone give me some feedback about my code?

I just want to know if this is the right approach, and how I can improve the tree. I am new to JavaScript and data structures.

function bst() {
    this.root = null;
}

bst.prototype.insert = function( obj ){

    if ( this.root == null ){
        this.root = new node(obj);
    }
    else if (this.root.value > obj){
         if (this.root.left != null ){
            this.root.left.insert( obj );
        }
        else {
            this.root.left = new node(obj);
        }
    } 
    else if (this.root.value < obj){
        if (this.root.right != null ){
            this.root.right.insert( obj );
        }
        else {
            this.root.right = new node(obj);
        }
    }
}

    function node( obj ){

   this.left = null;
    this.right = null;
    this.value = obj;

    }

node.prototype.insert = function( obj ){

if (this.value > obj){

    if (this.left != null){
        this.left.insert( obj )
    }
    else{
        this.left = new node(obj);
    }
}

else if (this.value < obj){

    if (this.right != null){
        this.right.insert( obj )
    }
    else{
        this.right = new node(obj);
    }
}
//elase duplicated key value
else{
    console.log("duplicated bst key")
}

}

var bst = new bst();
bst.insert(25);
bst.insert(75);
bst.insert(12);
bst.insert(37);
bst.insert(87);
bst.insert(63);

console.log(bst.root.value);
console.log(bst.root.left.value);
console.log(bst.root.right.value);
console.log(bst.root.right.left.value);
console.log(bst.root.right.right.value);
console.log(bst.root.right.left.right.value);
\$\endgroup\$

migrated from stackoverflow.com Jun 9 '14 at 12:29

This question came from our site for professional and enthusiast programmers.

2
\$\begingroup\$

I can see two obvious points:

  • Constructor names are usually capitalized, to indicate that they should be invoked with new
  • You've got some code duplication between bst::insert and node::insert. This even leads to the bug that you don't recognise/handle duplicate values in the root node.

So, I'd suggest:

function Bst() {
    this.root = null;
}
Bst.prototype.insert = function(obj) {
    if (this.root == null) {
        this.root = new Node(obj);
    } else {
        this.root.insert(obj);
    }
};

I am new to data structures.

Binary trees are a wide field :-) First, I'm missing some other basic operations like searching, traversing, and deleting. If you have mastered these, you can go on with optimizing your tree, e.g. making it a balanced one.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.