Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tejzpr
Created February 5, 2018 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tejzpr/0989d404e572921eadc50fdbeec52e48 to your computer and use it in GitHub Desktop.
Save tejzpr/0989d404e572921eadc50fdbeec52e48 to your computer and use it in GitHub Desktop.
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