Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Javascript Binary Tree
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
this.inorderOut = [];
this.preorderOut = [];
this.postorderOut = [];
}
insert(data) {
if(data < this.data) {
if(this.left != null) {
this.left.insert(data);
} else {
this.left = new Node(data);
}
} else {
if(this.right != null) {
this.right.insert(data);
} else {
this.right = new Node(data);
}
}
}
contains(item) {
if(item === this.data) {
return true;
}
if(item < this.data) {
if(this.left != null) {
return this.left.contains(item);
} else {
return false;
}
} else {
if(this.right != null) {
return this.right.contains(item);
} else {
return false;
}
}
}
inorder(out) {
if(!out) {
out=this.inorderOut;
}
if(this.left != null) {
this.left.inorder(out);
}
out.push(this.data);
if(this.right != null) {
this.right.inorder(out);
}
return this.inorderOut;
}
preorder(out) {
if(!out) {
out=this.preorderOut;
}
out.push(this.data);
if(this.left != null) {
this.left.preorder(out);
}
if(this.right != null) {
this.right.preorder(out);
}
return this.preorderOut;
}
postorder(out) {
if(!out) {
out=this.postorderOut;
}
if(this.left != null) {
this.left.postorder(out);
}
if(this.right != null) {
this.right.postorder(out);
}
out.push(this.data);
return this.postorderOut;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment