java中树的方法_Java中的通用树实现

是否有人知道JavaScript的通用树(节点可能有多个子代)实现?

它应该至少可以做这些事情,

>获取父节点.

>获取子节点.

>获取所有后代.

>删除所有后代.

>删除子节点.

一些实现类似于邻接列表模型.

背景:我需要为我的网页存储基于JavaScript的分层数据,但是我找不到通用树的良好JavaScript实现,所以我所做的是我使用Ajax使用Adjacency List Model和php将分层数据存储到数据库中.当用户在同一浏览器的两个选项卡中打开同一页面或在两种不同的浏览器中打开该页面时,就会出现问题,因为这两个实例都正在从同一表读取相同的表,这也引起了我任何可能的解决方法回答我的问题.

编辑:在任何时候,性能实际上都不是我的约束,我将不会有超过50个条目.

解决方法:

如果您需要更复杂的功能,则需要编写自己的库(或至少一个具有您所描述的所有方法的对象).

编辑:

这是我实现树功能的简单代码.删除所有后代并删除所有子代实际上是相同的…因此:

function Node(value) {

this.value = value;

this.children = [];

this.parent = null;

this.setParentNode = function(node) {

this.parent = node;

}

this.getParentNode = function() {

return this.parent;

}

this.addChild = function(node) {

node.setParentNode(this);

this.children[this.children.length] = node;

}

this.getChildren = function() {

return this.children;

}

this.removeChildren = function() {

this.children = [];

}

}

var root = new Node('root');

root.addChild(new Node('child 0'));

root.addChild(new Node('child 1'));

var children = root.getChildren();

for(var i = 0; i < children.length; i++) {

for(var j = 0; j < 5; j++) {

children[i].addChild(new Node('second level child ' + j));

}

}

console.log(root);

children[0].removeChildren();

console.log(root);

console.log(root.getParentNode());

console.log(children[1].getParentNode());

在Chrome(或支持控制台的其他浏览器)中运行它.

标签:tree,javascript

来源: https://codeday.me/bug/20191127/2076699.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值