From 083ddadd4bd207f421fe37164e3c471113c90181 Mon Sep 17 00:00:00 2001 From: chenshuai <2268380485@qq.com> Date: Sat, 12 Apr 2025 21:19:53 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B5=8B=E8=AF=95=E6=80=A7=E6=8F=90=E4=BA=A4:?= =?UTF-8?q?=E5=88=9B=E5=BB=BA=E4=B8=80=E4=B8=AA=E6=B5=8B=E8=AF=95=E6=80=A7?= =?UTF-8?q?=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/other/tree.js | 80 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 src/other/tree.js diff --git a/src/other/tree.js b/src/other/tree.js new file mode 100644 index 0000000..2498926 --- /dev/null +++ b/src/other/tree.js @@ -0,0 +1,80 @@ +// tree.js +// 实现一个树结构 +class Tree { + constructor(data) { + this.data = data; + this.children = []; + } +} +module.exports = Tree; +// 相关的方法 +// 插入子节点 +Tree.prototype.insert = function(data) { + this.children.push(new Tree(data)); +} +// 遍历树 +Tree.prototype.traverse = function(callback) { + callback(this.data); + for (let i = 0; i < this.children.length; i++) { + this.children[i].traverse(callback); + } +} +// 查找树 +Tree.prototype.find = function(data) { + if (this.data === data) { + return this; + } + for (let i = 0; i < this.children.length; i++) { + let result = this.children[i].find(data); + if (result) { + return result; + } + } + return null; +} +// 删除树 +Tree.prototype.remove = function(data) { + for (let i = 0; i < this.children.length; i++) { + if (this.children[i].data === data) { + this.children.splice(i, 1); + return; + } + } +} +// 清空树 +Tree.prototype.clear = function() { + this.children = []; +} +// 树的高度 +Tree.prototype.height = function() { + let height = 0; + for (let i = 0; i < this.children.length; i++) { + let childHeight = this.children[i].height(); + if (childHeight > height) { + height = childHeight; + } + } + return height + 1; +} +// 树的深度 +Tree.prototype.depth = function() { + let depth = 0; + let parent = this.parent; + while (parent) { + depth++; + parent = parent.parent; + } + return depth; +} +// 树的大小 +Tree.prototype.size = function() { + let size = 1; +} +// 树的叶子节点 +Tree.prototype.leaf = function() { + let leaf = 0; +} +// 树的节点数 +Tree.prototype.node = function() { + let node = 0; +}