本文翻译自:Java tree data-structure? [closed]

Is there a good available (standard Java) data structure to represent a tree in Java? 是否有一个良好的可用(标准Java)数据结构来表示Java中的树?

Specifically I need to represent the following: 具体来说,我需要代表以下内容:

  • The tree at any node can have an arbitrary number of children 任何节点上的树都可以有任意数量的子节点
  • Each node (after the root) is just a String (whose children are also Strings) 每个节点(在根之后)只是一个String(其子节点也是字符串)
  • I need to be able to get all the children (some sort of list or array of Strings) given an input string representing a given node 给定一个表示给定节点的输入字符串,我需要能够获得所有子节点(某种列表或字符串数​​组)

Is there an available structure for this or do I need to create my own (if so implementation suggestions would be great). 是否有可用的结构或我是否需要创建自己的结构(如果是这样的实现建议会很好)。


#1楼

参考:https://stackoom.com/question/EmLm/Java树数据结构-关闭


#2楼

您可以使用Java的任何XML API作为Document和Node..as XML是带有字符串的树结构


#3楼

No answer mentions over-simplified but working code, so here it is: 没有回答提到过度简化但工作的代码,所以这里是:

public class TreeNodeArray<T> {public T value;public final  java.util.List<TreeNodeArray<T>> kids =  new java.util.ArrayList<TreeNodeArray<T>>();
}

#4楼

Since the question asks for an available data structure, a tree can be constructed from lists or arrays: 由于该问题要求可用的数据结构,因此可以从列表或数组构造树:

Object[] tree = new Object[2];
tree[0] = "Hello";
{Object[] subtree = new Object[2];subtree[0] = "Goodbye";subtree[1] = "";tree[1] = subtree;
}

instanceof can be used to determine whether an element is a subtree or a terminal node. instanceof可用于确定元素是子树还是终端节点。


#5楼

Yet another tree structure: 另一种树形结构:

public class TreeNode<T> implements Iterable<TreeNode<T>> {T data;TreeNode<T> parent;List<TreeNode<T>> children;public TreeNode(T data) {this.data = data;this.children = new LinkedList<TreeNode<T>>();}public TreeNode<T> addChild(T child) {TreeNode<T> childNode = new TreeNode<T>(child);childNode.parent = this;this.children.add(childNode);return childNode;}// other features ...}

Sample usage: 样品用法:

TreeNode<String> root = new TreeNode<String>("root");
{TreeNode<String> node0 = root.addChild("node0");TreeNode<String> node1 = root.addChild("node1");TreeNode<String> node2 = root.addChild("node2");{TreeNode<String> node20 = node2.addChild(null);TreeNode<String> node21 = node2.addChild("node21");{TreeNode<String> node210 = node20.addChild("node210");}}
}

BONUS 奖金
See fully-fledged tree with: 查看完全成熟的树:

  • iterator 迭代器
  • searching 搜索
  • Java/C# 的Java / C#

https://github.com/gt4dev/yet-another-tree-structure https://github.com/gt4dev/yet-another-tree-structure


#6楼

You should start by defining what a tree is (for the domain), this is best done by defining the interface first. 您应该首先定义树是什么(对于域),最好先通过定义接口来完成。 Not all trees structures are modifyable, being able to add and remove nodes should be an optional feature, so we make an extra interface for that. 并非所有树结构都是可修改的,能够添加删除节点应该是一个可选功能,因此我们为此创建了一个额外的接口。

There's no need to create node objects which hold the values , in fact I see this as a major design flaw and overhead in most tree implementations. 没有必要创建保存值的节点对象 ,事实上我认为这是大多数树实现中的主要设计缺陷和开销。 If you look at Swing, the TreeModel is free of node classes (only DefaultTreeModel makes use of TreeNode ), as they are not really needed. 如果你看看Swing, TreeModel没有节点类(只有DefaultTreeModel使用TreeNode ),因为它们并不是真正需要的。

public interface Tree <N extends Serializable> extends Serializable {List<N> getRoots ();N getParent (N node);List<N> getChildren (N node);
}

Mutable tree structure (allows to add and remove nodes): 可变树结构(允许添加和删除节点):

public interface MutableTree <N extends Serializable> extends Tree<N> {boolean add (N parent, N node);boolean remove (N node, boolean cascade);
}

Given these interfaces, code that uses trees doesn't have to care much about how the tree is implemented. 给定这些接口,使用树的代码不必太在意树的实现方式。 This allows you to use generic implementations as well as specialized ones, where you realize the tree by delegating functions to another API. 这允许您使用通用实现以及专用实现,您可以通过将函数委托给另一个API来实现树。

Example: file tree structure 示例: 文件树结构

public class FileTree implements Tree<File> {@Overridepublic List<File> getRoots() {return Arrays.stream(File.listRoots()).collect(Collectors.toList());}@Overridepublic File getParent(File node) {return node.getParentFile();}@Overridepublic List<File> getChildren(File node) {if (node.isDirectory()) {File[] children = node.listFiles();if (children != null) {return Arrays.stream(children).collect(Collectors.toList());}}return Collections.emptyList();}
}

Example: generic tree structure (based on parent/child relations): 示例: 通用树结构 (基于父/子关系):

public class MappedTreeStructure<N extends Serializable> implements MutableTree<N> {public static void main(String[] args) {MutableTree<String> tree = new MappedTreeStructure<>();tree.add("A", "B");tree.add("A", "C");tree.add("C", "D");tree.add("E", "A");System.out.println(tree);}private final Map<N, N> nodeParent = new HashMap<>();private final LinkedHashSet<N> nodeList = new LinkedHashSet<>();private void checkNotNull(N node, String parameterName) {if (node == null)throw new IllegalArgumentException(parameterName + " must not be null");}@Overridepublic boolean add(N parent, N node) {checkNotNull(parent, "parent");checkNotNull(node, "node");// check for cyclesN current = parent;do {if (node.equals(current)) {throw new IllegalArgumentException(" node must not be the same or an ancestor of the parent");}} while ((current = getParent(current)) != null);boolean added = nodeList.add(node);nodeList.add(parent);nodeParent.put(node, parent);return added;}@Overridepublic boolean remove(N node, boolean cascade) {checkNotNull(node, "node");if (!nodeList.contains(node)) {return false;}if (cascade) {for (N child : getChildren(node)) {remove(child, true);}} else {for (N child : getChildren(node)) {nodeParent.remove(child);}}nodeList.remove(node);return true;}@Overridepublic List<N> getRoots() {return getChildren(null);}@Overridepublic N getParent(N node) {checkNotNull(node, "node");return nodeParent.get(node);}@Overridepublic List<N> getChildren(N node) {List<N> children = new LinkedList<>();for (N n : nodeList) {N parent = nodeParent.get(n);if (node == null && parent == null) {children.add(n);} else if (node != null && parent != null && parent.equals(node)) {children.add(n);}}return children;}@Overridepublic String toString() {StringBuilder builder = new StringBuilder();dumpNodeStructure(builder, null, "- ");return builder.toString();}private void dumpNodeStructure(StringBuilder builder, N node, String prefix) {if (node != null) {builder.append(prefix);builder.append(node.toString());builder.append('\n');prefix = "  " + prefix;}for (N child : getChildren(node)) {dumpNodeStructure(builder, child, prefix);}}
}

Java树数据结构? [关闭]相关推荐

  1. 常见数据结构和算法实现(排序/查找/数组/链表/栈/队列/树/递归/海量数据处理/图/位图/Java版数据结构)

    常见数据结构和算法实现(排序/查找/数组/链表/栈/队列/树/递归/海量数据处理/图/位图/Java版数据结构) 数据结构和算法作为程序员的基本功,一定得稳扎稳打的学习,我们常见的框架底层就是各类数据 ...

  2. Java常见数据结构以及特点、使用场景

    Java常见数据结构以及特点 Java中常见的数据结构,主要分为Collection和Map两种主要接口,程序中的数据结构是继承这些接口的数据结构类. Collection接口: List 接口继承: ...

  3. Java数据结构类如何使用_Matlab如何使用Java的数据结构类型

    Matlab 2008b才开始引入containers.Map,这是Matlab唯一的数据结构(这里的数据结构是指自带一定逻辑性的数据结构,不包括普通数据类型).如果要有其它,比如Queue.Set等 ...

  4. java堆 数据结构 堆_快速堆数据结构

    java堆 数据结构 堆 In this tutorial, we'll be discussing and implementing Heap data structures in Swift. 在 ...

  5. 树的数据结构代码_如何以无代码方式学习树数据结构

    树的数据结构代码 The tree data structure can form some of the most useful and complex data structures in all ...

  6. 【赫夫曼树数据结构及其应用】

    本文主要介绍Java中赫夫曼树数据结构的基本原理.实现方式以及使用场景.赫夫曼树(Huffman Tree)是一种带权路径最短的二叉树,广泛应用于数据压缩和编码等领域. 一.赫夫曼树的基本概念 赫夫曼 ...

  7. 数据结构树高度_树数据结构的高度

    数据结构树高度 In this tutorial, we'll be discussing Binary Trees. We'll see how to calculate the height of ...

  8. 数据结构显示树的所有结点_您需要了解的有关树数据结构的所有信息

    数据结构显示树的所有结点 When you first learn to code, it's common to learn arrays as the "main data struct ...

  9. java堆 数据结构 堆_Java中的紧凑堆外结构/组合

    java堆 数据结构 堆 在上一篇文章中,我详细介绍了代码对主内存的访问方式的含义. 从那时起,我就在Java中可以做什么以实现更可预测的内存布局提出了很多疑问. 有些模式可以使用数组支持的结构来应用 ...

最新文章

  1. 如何在MyEclipse中将项目部署Tomcat
  2. Linux如何建立用户(组)及调整用户(组)属性(案列+详细指令)
  3. 11月1日至11日 全国处理快件47.76亿件
  4. Pomelo:网易开源基于 Node.js 的游戏服务端框架
  5. WPF 3D:简单的Point3D和Vector3D动画创造一个旋转的正方体
  6. WinForm编程开发实用技巧14则(转)
  7. PN532读写卡器(支持NFC、RFID)
  8. 小宁百度了php一句话,赛宁平台web题解(一)
  9. 前端页面性能优化的几种方式(强烈推荐)
  10. 攻防世界backup
  11. java盘盈盘亏_反映财产物资的盘盈、盘亏和毁损情况,应当设( )科目。
  12. Android 贝塞尔曲线实战之网易云音乐鲸云特效,2021程序员进阶宝典
  13. 用于智能机械故障诊断的鲁棒权值共享胶囊网络(学习记录)
  14. 2023年4月中国数据库排行榜:达梦厚积薄发夺探花,亚信、星环勇毅笃行有突破
  15. upload-labs安装及攻略
  16. 在word中插入显示在同一行的两张图片(且各自带有题注)
  17. 蓝桥杯1——李白打酒加强版
  18. 华为p9 Android6 备份,华为手机怎么备份?华为手机备份数据教程
  19. oracle 同义词 synonym 创建与删除表
  20. 2D激光雷达:使用MindStudio进行MindX SDK任务开发

热门文章

  1. 《海量日志数据分析与应用》场景介绍及技术点分析
  2. 01-C#入门(分支控制语句)
  3. 程序自动化需要一个Windows服务
  4. innodb_file_format设置
  5. JEECG传统版问题分析
  6. Chrome浏览器快速获取静态控件的XPATH
  7. NetBSD Make源代码阅读二:链表之创建与销毁
  8. PHP JSON中文乱码解决方法大全
  9. Nexpose漏扫使用步骤
  10. Web中间件常见安全漏洞总结