Created
February 5, 2018 21:53
-
-
Save tejzpr/0989d404e572921eadc50fdbeec52e48 to your computer and use it in GitHub Desktop.
Javascript Binary Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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