I'm creating a program to represent a binary search tree in javascript. What I want is a way to create a common tree node with both ptrs(left, right) as null. This is the code i wrote:
var BST = function(data) {
if (data === null || data === undefined){
this.data = null;
this.left = null;
this.right = null;
}
else{
this.data = data;
this.left = new BST(null);
this.right = new BST(null);
}
};
BST.prototype.insert = function(data) {
if (this.data === null){
this.data = data;
this.left = new BST(null);
this.right = new BST(null);
}
else if (data < this.data)
this.left.insert(data);
else if (data > this.data)
this.right.insert(data);
};
BST.prototype.inOrder = function(func) {
if (this.data !== null) {
this.left.inOrder(func);
func(this.data);
this.right.inOrder(func);
}
};
Here, i want to assign all null pointers with a null node(as defined in the if(data === null || data === undefined)
condition). But for every null node I'm having to create a new node representing the same data.
Is there a way to assign to a common instance of the null node?
The reason i use a null node instead of just using
else{
this.data = data;
this.left = null;
this.right = null;
}
is that on calling the inOrder
method, on reaching a node with left or right = null
, it gives a TypeError
because it tries to run null.inOrder(func);
since, this.left
translates to null
.
The way around that is to modify the inOrder
function, which will lead to many conditions around each statement, i.e. not a very elegant implementation.
I could also define inOrder
outside the prototype of the object, and make it take a tree as an argument i.e. inOder(tree,func)
, but I don't want to do that.
Also, as a second improvement to the code, consider the insert
method; in the null
case:
if (this.data === null){
this.data = data;
this.left = new BST(null);
this.right = new BST(null);
}
since I have to override each entry anyway, I want to reassign this node to a new Tree altogether by doing something along the lines of:
if (this.data === null)
this = new BST(data);
I am aware that this would be a less efficient implementation to the former, but it is still a lot more concise.So is there any way to do so?