How to implement a tree data-structure in Java?

前端 未结 24 2457
鱼传尺愫
鱼传尺愫 2020-11-22 00:27

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

Specifically I need to represent the following:

  • The sub-tree at any node can have
24条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 00:55

    Here:

    public class Tree {
        private Node root;
    
        public Tree(T rootData) {
            root = new Node();
            root.data = rootData;
            root.children = new ArrayList>();
        }
    
        public static class Node {
            private T data;
            private Node parent;
            private List> children;
        }
    }
    

    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.

    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.

提交回复
热议问题