function Node(data,left,right){
this.data = data
this.left = left
this.right = right
}
function BST(){
this.root = null
}
BST.prototype.insert = function(data){
var node = new Node(data,null,null)
if(!this.root) {
this.root = node
}else {
var current = this.root,parent = null
while(true) {
parent = current
if(data < current.data) {
current = current.left
if(!current) {
return parent.left = node
}
}else {
current = current.right
if(!current) {
return parent.right = node
}
}
}
}
}
BST.prototype.inOrder = function(node){
if(node) {
this.inOrder(node.left)
console.log(node.data)
this.inOrder(node.right)
}
}
BST.prototype.preOrder = function(node){
if(node) {
console.log(node.data)
this.inOrder(node.left)
this.inOrder(node.right)
}
}
BST.prototype.postOrder = function(node){
if(node) {
this.inOrder(node.left)
this.inOrder(node.right)
console.log(node.data)
}
}
BST.prototype.getMin = function(){
var current = this.root
while(current.left){
current = current.left
}
return current.data
}
BST.prototype.getMax = function(){
var current = this.root
while(current.right){
current = current.right
}
return current.data
}
BST.prototype.find = function(data){
var current = this.root
while(current){
if(current.data === data){
return current
}
if(current.data > data) {
current = current.left
}
if(current.data < data) {
current = current.right
}
}
return null
}
var Bst = new BST()
Bst.insert(1)
Bst.insert(2)
Bst.insert(4)
Bst.insert(1)
console.log(Bst.find(4))
console.log(Bst.getMax())
console.log(Bst.getMin())
原文:https://www.cnblogs.com/seny-33/p/12927284.html