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; //中序遍历,先左后中最后右
this.preOrder = preOrder; //先序遍历,先中后左最后右
this.postOrder = postOrder; //后序遍历,先左后右最后中
this.getMin = getMin; //只需遍历左子树,直到找到最后一个节点
this.getMax = getMax; //只需遍历右子树,直到找到最后一个节点
this.find = find;
}
function insert(data){
var n = new Node(data, null, null);
if(this.root == null){
this.root = n;
}else{
var current = this.root;
var parent = null;
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);
inorder += node.show() + " ";
log(inorder);
inOrder(node.right);
}
}
function preOrder(node){
if(node != null){
preorder += node.show() + " ";
log(preorder);
preOrder(node.left);
preOrder(node.right);
}
}
function postOrder(node){
if(node != null){
postOrder(node.left);
postOrder(node.right);
postorder += node.show() + " ";
log(postorder);
}
}
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 find(data){
var current = this.root;
while(current != null){
if(current.data == data){
return current;
}else if(data < current.data){
current = current.left;
}else{
current = current.right;
}
}
return null;
}
// start
var log = console.log;
var inorder = "";
var preorder = "";
var postorder = "";
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);
log("中序遍历:");
nums.inOrder(nums.root);
log("");
log("先序遍历:");
nums.preOrder(nums.root);
log("");
log("后序遍历:");
nums.postOrder(nums.root);
log("");
log("最小值为:");
log(nums.getMin());
log("");
log("最大值为:");
log(nums.getMax());
log("");
var value = 23;
log("查找值 " + value + ":");
if(nums.find(value)){
log("找到值 " + value);
}else{
log("不存在值 " + value);
}
log("");
var value = 33;
log("查找值 " + value + ":");
if(nums.find(value)){
log("找到值 " + value);
}else{
log("不存在值 " + value);
}
14、二叉树
最新推荐文章于 2020-01-09 17:23:08 发布