如何在Java中实现树型数据结构? [英] How to implement a tree data-structure in Java?

查看:621
本文介绍了如何在Java中实现树型数据结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有标准的Java库类来表示Java中的树?

Is there any standard Java library class to represent a tree in Java?

具体来说,我需要代表以下内容:

Specifically I need to represent the following:

  • 任何节点上的子树可以具有任意数量的子代
  • 每个节点(在根之后)及其子节点将具有字符串值
  • 我需要获取给定节点的所有子节点(某种形式的列表或字符串数​​组),它是字符串值(即一种方法,它将一个节点作为输入并返回所有子节点的字符串值作为输出)

是否有任何可用的结构,或者我需要创建自己的结构(如果这样的话,实施建议会很好).

Is there any available structure for this or do I need to create my own (if so implementation suggestions would be great).

推荐答案

此处:

public class Tree<T> {
    private Node<T> root;

    public Tree(T rootData) {
        root = new Node<T>();
        root.data = rootData;
        root.children = new ArrayList<Node<T>>();
    }

    public static class Node<T> {
        private T data;
        private Node<T> parent;
        private List<Node<T>> children;
    }
}

这是可用于String或任何其他对象的基本树结构.实施简单的树来完成您需要的工作相当容易.

That is a basic tree structure that can be used for String or any other object. It is fairly easy to implement simple trees to do what you need.

您需要添加的只是用于添加,删除,遍历和构造方法的方法. NodeTree的基本构建块.

All you need to add are methods for add to, removing from, traversing, and constructors. The Node is the basic building block of the Tree.

这篇关于如何在Java中实现树型数据结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆