二叉树
树的定义
二叉树和二叉查找树
实现二叉查找树
二叉查找树: 相对小的值保存在左节点 大的值保存的右节点
function Node(data, left, right) {
this.data = data;
this.left = left;
this.right = right;
this.show = function () {
return this.data
}
}
function BST() {
this.root = null
this.insert = function (data) {
var n = new Node(data, null, null)
if (this.root == null) {
this.root = n
} else {
var current = this.root
var parent;
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;
}
}
}
}
}
this.inOrder = function (node) {
if (!(node == null)) {
this.inOrder(node.left)
console.log(node.show())
this.inOrder(node.right)
}
}
this.preOrder = function(node) {
if (!(node == null)) {
console.log(show())
preOrder(node.left)
preOrder(node.right)
}
}
this.preOrder = function(node) {
if (!(node == null)) {
preOrder(node.left)
preOrder(node.right)
console.log(show())
}
}
}
var nums = new BST()
nums.insert(23)
nums.insert(45)
nums.insert(23)
nums.insert(37)
nums.insert(3)
nums.inOrder(nums.root)
遍历
根据根节点位置
- 前序
- 后序
- 中序
this.inOrder = function (node) {
if (!(node == null)) {
this.inOrder(node.left)
console.log(node.show())
this.inOrder(node.right)
}
}
this.preOrder = function(node) {
if (!(node == null)) {
console.log(show())
preOrder(node.left)
preOrder(node.right)
}
}
this.preOrder = function(node) {
if (!(node == null)) {
preOrder(node.left)
preOrder(node.right)
console.log(show())
}
}
查找
查找最小值和最大值
BST上最小值 只需要一直查找他的左子节点 最左边的值就是最小值
getMin() {
var current = this.root
while(!(current.left == null)) {
current = current.left
}
return current.data
}
最大值同理
getMax() {
var current = this.root
while(!(current.right == null)) {
current = current.right
}
return current.data
}
查找指定值
比较当前值和节点值得大小,选择一种遍历方法
this.find = function(data) {
var current = this.root
while(current != null) {
if(current.data == data) {
return current
} else if (data < current.data) {
current = current.left
} else if (data > current.data) {
current = current.right
}
}
return null
}
删除节点
- 当删除子节点时最为简单 返回null
- 删除节点含有一个子节点,将他得的父节点指向子节点
- 删除含有两个子节点的节点,要么查找左子树的最大值,要么查找右子树的最小值
this.remove = function(data) {
root = removeNode(this.root, data)
}
this.removeNode = function(node, data) {
if(node == null) {
return null
}
if(data == node.data) {
if(node.left == null && node.right == null) {
return null
}
if(node.left == null) {
return node.right
}
if(node.right == null) {
return node.left
}
var temp = getMin(node.right)
node.data = temp.data
node.right = removeNode(node.right, tempNode.data)
return node
} else if (data < node.data) {
node.left = removeNode(node.left, data)
return node
} else {
node.right = removeNode(node.right, data)
return node
}
}
计数
将一组数据加入到一个BST中,如果数据重复就count+1 如果没有数据就创建一个新的节点保存数据
this.count = 1
this.update = function(data) {
var node = this.find(data)
node.count++
return node
}