#Data Structure - Binary Tree @(Data Structure & Algorithm)
function Node(key,parent,left,right){
this.key = key;
this.parent = parent;
this.left = left;
this.right = right;
}
Node.prototype = {
constructor: Node,
display: function(){
var parent = (this.parent !== null) ? this.parent.key : "null";
var left = (this.left !== null) ? this.left.key : "null";
var right = (this.right !== null) ? this.right.key : "null";
console.log("Key: " + this.key + " Parent: " + parent + " Left: " + left + " Right: " + right);
}
};
//二叉查找树
//较小的值插入到左节点
function BST(){
this.root = null;
}
BST.prototype = {
constructor: BST,
insert: function(key){
var node = new Node(key, null, null, null);
if (this.root === null){
this.root = node;
return true;
}
var p = this.root;
while (true){
if (key < p.key){
if (p.left === null){
p.left = node;
node.parent = p;
return true;
}
p = p.left;
continue;
} else{
if (p.right === null){
p.right = node;
node.parent = p;
return true;
}
p = p.right;
continue;
}
}
return false;
},
//inorder tree walk
itw: function(p){
if (p !== null){
this.itw(p.left);
p.display();
this.itw(p.right);
}
return true;
},
//preorder
pretw: function(p){
if (p !== null){
p.display();
this.itw(p.left);
this.itw(p.right);
}
return true;
},
//postorder
posttw: function(p){
if (p !== null){
this.itw(p.left);
this.itw(p.right);
p.display();
}
return true;
},
find: function(key){
var n = this.root;
while (n !== null) {
if (key < n.key){
n = n.left;
continue;
} else if (key > n.key){
n = n.right;
continue;
} else{
return n;
}
}
return false;
},
max: function(){
var n = this.root;
while (n.right !== null){
n = n.right;
}
n.display();
},
min: function(){
var n = this.root;
while (n.left !== null){
n = n.left;
}
n.display();
},
replace: function(prevNode,postNode){
prevNode.key = postNode.key;
prevNode.left = postNode.left;
prevNode.right = postNode.right;
return true;
},
replaceKey: function(prevNode,postNode){
prevNode.key = postNode.key;
return true;
},
removeLeafNode: function(node){
var p = node.parent;
if (p.left === node){
p.left = null;
return true;
}
p.right = null;
return true;
},
remove: function(key){
var node = this.find(key);
if (node){
if (node.left === null){
if (node.right === null){
this.removeLeafNode(node);
} else {
this.replace(node,node.right);
}
} else {
if (node.left.right === null){
this.replace(node, node.left);
} else {
var maxNode = node.left.right;
while (maxNode.right !== null){
maxNode = maxNode.right;
}
this.replaceKey(node, maxNode);
this.removeLeafNode(maxNode);
}
}
return true;
} else {
return false;
}
}
};
var arr = [49,63,51,81,55,60];
var t = new BST();
for (var i = 0; i < arr.length; i++){
t.insert(arr[i]);
}
//tree walk
console.log("inorder");
t.itw(t.root);
console.log("---");
//remove node
t.remove(63);
t.itw(t.root);