var Node = (function() {
function Node(data, left, right, parent) {
this.data = data;
this.left = left;
this.right = right;
this.parent = parent;
}
Node.prototype = {
constructor: Node,
show: function() {
return this.data
}
}
return Node
})()
var OrderTree = (function() {
function OrderTree() {
this.root = null
}
OrderTree.prototype = {
constructor: OrderTree,
create: create,
insert: insert,
remove: remove,
disp: disp,
sortMin: sortMin,
sortMax: sortMax,
search: search,
getMin: getMin,
getMax: getMax
}
function create(datalist) {
var i = 0
while(i < datalist.length) {
this.insert(datalist[i++])
}
return this.root
}
function insert(data) {
if(!this.root) {
this.root = new Node(data, null, null, null)
return
}
var _insert = function(node) {
if(node.left && data < node.data) {
return _insert(node.left)
} else if(node.right && data >= node.data) {
return _insert(node.right)
} else if(!node.left && data < node.data) {
node.left = new Node(data, null, null, node)
} else {
node.right = new Node(data, null, null, node)
}
}
_insert(this.root)
}
function remove(value) {
var re = this.search(value)
if(re.constructor.name === '_Node') {
var p = re.parent
if(re === p.left) {
delete p.left
p.left = null
} else {
delete p.right
p.right = null
}
}
}
function sortMin() {
if(!this.root) {
console.log('空树')
return
}
var a = []
var pre = function(n) {
if(n) {
pre(n.left)
a.push(n.data)
return pre(n.right)
}
}
pre(this.root)
return a
}
function sortMax() {
return this.sortMin().reverse()
}
function search(value) {
var n = '没有找到 ' + value
var _search = function(node) {
if(node) {
if(value === node.data) {
n = node
return
} else if(node.left && value < node.data) {
return _search(node.left)
} else if(value > node.data) {
return _search(node.right)
}
}
}
_search(this.root)
return n
}
function getMin(){
var current = this.root;
while(!(current.left == null)){
current = current.left;
}
return current.data;
}
function getMax(){
var current = this.root;
while(!(current.right == null)){
current = current.right;
}
return current.data;
}
function disp() {
if(!this.root) {
console.log('空树')
} else {
console.log(this.root)
}
}
return OrderTree
})()
var t = new OrderTree()
t.create([1,10,2,0,3,-100,200])
console.log(t.sortMin());
t.remove(0)
t.insert(520)
console.log(t.sortMin());