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);
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jun 8, 2014 at 16:16
\$\endgroup\$
0

1 Answer 1

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.

answered Jun 8, 2014 at 18:21
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.