Merge pull request '陈帅创建了一个树' (#1) from test into main
commit
0dd2074c78
@ -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;
|
||||
}
|
Loading…
Reference in new issue