js定义二叉查找树
//创建构造函数创建节点
function Node(data){
this.data = data;
this.left = null;
this.right = null;
}
function tree(){
this.root = null;
this.insert = insert;
this.inOrder = inOrder;
this.preOrder = preOrder;
this.postOrder = postOrder;
}
function insert(data){
var n = new Node(data);
if(this.root == null){
this.root = n;
}else{
var cur = this.root;
while (true){
if(data < cur.data){
if(cur.left == null){
cur.left = n;
break;
}else{
cur = cur.left;
}
}else{
if(cur.right == null){
cur.right = n;
break;
}else{
cur = cur.right;
}
}
}
}
}
//中序遍历
function inOrder(node){
var str = '';
if(node != null){
inOrder(node.left);
str = node.data;
console.log(str);
inOrder(node.right);
}
}
//先序遍历
function preOrder(node){
var str = '';
if(node != null){
str = node.data;
console.log(str);
preOrder(node.left);
preOrder(node.right);
}
}
//后序遍历
function postOrder(node){
var str = '';
if(node != null){
postOrder(node.left);
postOrder(node.right);
str = node.data;
console.log(str);
}
}
查找最小值最大值
思路:遍历左子树,取最后一个值,得到最小值;遍历右子树,取最后一个值,得到最大值
function getMin(){
var cur = this.root;
while (cur.left != null){
cur = cur.left;
}
return cur.data;
}
function getMax(){
var cur = this.root;
while (cur.right != null){
cur = cur.right;
}
return cur.data;
}
查找给定值
function find(data){
var cur = this.root;
while(cur != null){
if(cur.data == data){
return true;
}else if(cur.data < data){
cur = cur.right;
}else{
cur = cur.left;
}
}
return false;
}