14、二叉树

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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值