使用 Javascript 实现各种树算法
admin 阅读:81 2024-08-12

简单的树
- 我们需要始终从简单的算法开始,然后一步步走向复杂的算法。
- 简单的树
- 二叉树
class simpletree {
constructor(value) {
this.value = value;
this.children = [];
}
insertchild(value) {
const newchild = new simpletree(value);
const lastelement = this.findlastchild(this);
lastelement.children.push(newchild);
return newchild;
}
findlastchild(root) {
if (root.children.length == 0) {
return root;
}
return this.findlastchild(root.children[0]);
}
traversal(root) {
console.log(root.value + ' --> ');
root.children.foreach(child => {
this.traversal(child);
})
}
}
const simpletree = new simpletree('a');
simpletree.insertchild('b');
simpletree.insertchild('c');
simpletree.insertchild('d');
simpletree.insertchild('e');
simpletree.insertchild('f');
console.log(simpletree)
simpletree.traversal(simpletree)
/*
{
"value": "a",
"children": [
{
"value": "b",
"children": [
{
"value": "c",
"children": [
{
"value": "d",
"children": [
{
"value": "e",
"children": [
{
"value": "f",
"children": []
}
]
}
]
}
]
}
]
}
]
}
*/
二叉树
class BinaryTree {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
insertNode(value) {
const newNode = new BinaryTree(value);
const {node: lastNode, side} = this.findAppropriatePlace(this, value);
lastNode[side] = newNode;
return newNode;
}
removeFromNode(value) {
this.findAppropriateNodAndrRemove(this, value);
}
findAppropriateNodAndrRemove(root, value) {
const side = root.value
声明
1、部分文章来源于网络,仅作为参考。 2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!



