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
//https://www.cs.usfca.edu/~galles/visualization/BST.html | |
function Node(data, left, right){ | |
this.data = data; | |
this.left = left; | |
this.right = right; | |
this.show = show; | |
} | |
function show(){ | |
return this.data; | |
} | |
function BST(){ | |
this.root = null; | |
this.insert = insert; | |
this.inOrder = inOrder; | |
} | |
function insert(data){ | |
var n = new Node(data, null, null); | |
if(this.root == null){ | |
this.root = n; | |
} | |
else{ | |
var current = this.root; | |
var parent; | |
while(true){ | |
parent = current; | |
if(data<current.data){ | |
current = current.left; | |
if(current == null){ | |
parent.left = n; | |
break; | |
} | |
} | |
else{ | |
current = current.right; | |
if(current == null){ | |
parent.right = n; | |
break; | |
} | |
} | |
} | |
} | |
} | |
function inOrder(node){ | |
if(!(node == null)){ | |
inOrder(node.left); | |
console.log(node.data); | |
inOrder(node.right); | |
} | |
} | |
var nums = new BST(); | |
nums.insert(23); | |
nums.insert(45); | |
nums.insert(16); | |
nums.insert(37); | |
nums.insert(3); | |
nums.insert(99); | |
nums.insert(22); | |
console.log("Inorder traversal: "); | |
inOrder(nums.root); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment