JavaScript实现二叉查找树

本文介绍了一种二叉搜索树的实现方法,包括节点定义、插入操作、遍历(中序、前序、后序)、查找最小及最大值等功能。通过具体代码示例展示了二叉搜索树的基本操作。

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.left == 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);
print(node.show());
inOrder(node.right);
}
}


function preOrder(node) {
if (node != null) {
print(node.show());
preOrder(node.left);
preOrder(node.rigth);
}
}


function postOrder(node) {
if (node != null) {
postOrder(node.left);
postOrder(node.right);
print(node.show());
}
}

 


function getMin() {
var current = this.root;
if (current == null) {
return false;
}
while (!(current.left == null)) {
current = current.left;
}
return current.data;
}


function getMan() {

var current = this.root;
if (current == null) {
return false;
}
while (!(current.right == null)) {
current = current.right;
}
return current.data;
}


function findData(data) {
var current = this.root;
while (!(current== null)) {
if (current.data == data) {
return true;
}
else if (current.data > data) {
current = current.left;
}
else
{
current = current.right;
}
return false;
}
}

 

转载于:https://www.cnblogs.com/aobama/p/4347010.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值