首页 > 其他分享 >数据结构137-二叉搜索树-先序遍历代码

数据结构137-二叉搜索树-先序遍历代码

时间:2023-02-11 12:02:51浏览次数:56  
标签:node function right 二叉 137 先序 key newNode null


<!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>

标签:node,function,right,二叉,137,先序,key,newNode,null
From: https://blog.51cto.com/u_15460007/6050169

相关文章