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

查看:45
本文介绍了如何在 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天全站免登陆