<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
function BinaryTree() {
var Node = function(key) {//节点
this.key = key;
this.left = null;
this.right = null;
};
var root = null;//初始化根节点为空
var insertNode = function(node, newNode) { //插入节点
if (newNode.key < node.key) {
if (node.left === null) {
node.left = newNode;
} else {
insertNode(node.left, newNode);
}
} else {
if (node.right === null) {
node.right = newNode;
} else {
insertNode(node.right, newNode);
}
}
}
this.insert = function(key) {
var newNode = new Node(key);
if (root === null) {
root = newNode;
} else {
insertNode(root, newNode);
}
};
var inOrderTraverseNode = function(node, callback) {//中序遍历
if (node !== null) {
inOrderTraverseNode(node.left, callback);
callback(node.key);
inOrderTraverseNode(node.right, callback);
}
}
this.inOrderTraverseNode = function(callback) {
inOrderTraverseNode(root, callback);
}
var minNode = function(node) {
if (node) {
while (node && node.left !== null) {
node = node.left;
}
return node.key;
}
}
this.min = function() {
return minNode(root);
}
var searchNode = function(node, key) {//查找某节点是否存在
if (node === null) {
return false;
}
if (key < node.key) {
return searchNode(node.right, key);
} else if (key > node.key) {
return searchNode(node.left, key);
} else {
return true;
}
}
this.search = function(key) {
return searchNode(root, key);
}
var findMinNode = function(node) {
if (node) {
while (node && node.left !== null) {
node = node.left;
}
return node;
}
return null;
}
var removeNode = function(node, key) {//删除节点
if (node === null) {
return null;
}
if (key < node.key) {
node.left = removeNode(node.left, key);
return node;
} else if (key > node.key) {
node.right = removeNode(node.right, key);
return node;
} else {
if (node.left === null && node.right === null) {
node = null;
return node;
}
if (node.left === null) {
node = node.right;
return node;
} else if (node.right === null) {
node = node.left;
return node;
}
var aux = findMinNode(node.right);
node.key = aux.key;
node.right = removeNode(node.right, aux.key);
return node;
}
}
this.remove = function(key) {
root = removeNode(root, key);
}
}
var nodes = [8, 3, 10, 1, 6, 14, 4, 7, 13];
var binaryTree = new BinaryTree();//初始化
nodes.forEach(function(key) {
binaryTree.insert(key);
});
var callback = function(key) {
console.log(key);
}
binaryTree.inOrderTraverseNode(callback);
console.log(binaryTree.min());
console.log(binaryTree.search(8) ? '有' : '没有');
binaryTree.remove(6);
binaryTree.inOrderTraverseNode(callback);
</script>
</head>
<body>
</body>
</html>
JavaScript实现二叉树
最新推荐文章于 2025-04-15 11:38:22 发布