<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>封装二叉搜索树</title>
</head>
<body>
<script>
function BinarySearchTree(){
function Node(key){
this.key=null
this.left=null
this.right-null
}
this.root=null
BinarySearchTree.prototype.insert=function(key){
var newNode=new Node(key)
//判断节点是否有值
if(this.root==null){
this.root=newNode
}else{
this.insertNode(this.root,newNode)
}
}
BinarySearchTree.prototype.insertNode=function(node,newNode){
if(newNode.key<node.key){
if(node.left==null){
node.left=newNode
}else{
this.insertNode(node.left,newNode)
}
}else{
if(node.right==null){
node.right=newNode
}else{
this.insertNode(node.right,newNode)
}
}
}
//先序遍历
BinarySearchTree.prototype.preOrderTraversal=function(){
THIS.preOrderTraversalNode(this.root,handler)
}
BinarySearchTree.prototype.preOrderTraversalNode=function(node,handler){
if(node!=null){
//处理经过的节点
handler(node.key)
this.preOrderTraversalNode(node.left,handler)
this.preOrderTraversalNode(node.right,handler)
}
}
}
</script>
</body>
</html>