今天实现一下二叉树
/**
* 二叉树
* 二叉链表
*/
function Node(data){
this.data = data
this.left = null
this.right = null
}
class Bst {
constructor(){
this.root = null
}
/**
* 首先创建一个节点,判断是否有根节点
* 根据值的大小往左右节点查找,直到找到空节点(null)为止
* 这个新的节点就插在这个空节点的位置
*/
insert(data){
let newNode = new Node(data)
if(this.root === null){
this.root = newNode
}else{
let current = this.root
let parent
/**从根节点向下查到,找到空节点 为止, 得到parent */
while(current){
parent = current
if(data < current.data){
current = current.left
}else{
current = current.right
}
}
// 通过上面找到的parent和 新值做对比,决定放在左还是右
if(data < parent.data){
parent.left = newNode
}else{
parent.right = newNode
}
}
}
// 查找最小值,即在左边树查找, 最大值则相反
min(){
if(this.root == null) return null
let current = this.root
while(current.left !== null){
current = current.left
}
return current.data
}
find(data){
let current = this.root
while(current !== null){
if(current.data == data){
return current
}
if(current.data > data){
current = current.left
}else{
current = current.right
}
}
return null
}
}
// 遍历 ,更加根节点的遍历循序
function preOrder(node){
if(node === null) return
if(typeof node == 'undefined'){
node = this.root;
}
console.log(node.data)
preOrder(node.left)
preOrder(node.right)
}
function midOrder(node){
if(node === null) return
if(typeof node == 'undefined'){
node = this.root;
}
midOrder(node.left)
console.log(node.data)
midOrder(node.right)
}
function backOrder(node){
if(node === null) return
if(typeof node == 'undefined'){
node = this.root;
}
backOrder(node.left)
backOrder(node.right)
console.log(node.data)
}
let a = new Bst()
a.insert(11);
a.insert(3);
a.insert(5);
a.insert(1);
// console.log(a,a.root, a.left, a.right)
console.log(preOrder(a.root))
console.log(midOrder(a.root))
console.log(backOrder(a.root))
网友评论