How to implement a tree data-structure in Java?

前端 未结 24 2516
鱼传尺愫
鱼传尺愫 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:47

    I wrote a small "TreeMap" class based on "HashMap" that supports adding paths:

    import java.util.HashMap;
    import java.util.LinkedList;
    
    public class TreeMap extends LinkedHashMap> {
    
        public void put(T[] path) {
            LinkedList list = new LinkedList<>();
            for (T key : path) {
                list.add(key);
            }
            return put(list);
        }
    
        public void put(LinkedList path) {
            if (path.isEmpty()) {
                return;
            }
            T key = path.removeFirst();
            TreeMap val = get(key);
            if (val == null) {
                val = new TreeMap<>();
                put(key, val);
            }
            val.put(path);
        }
    
    }
    

    It can be use to store a Tree of things of type "T" (generic), but does not (yet) support storing extra data in it's nodes. If you have a file like this:

    root, child 1
    root, child 1, child 1a
    root, child 1, child 1b
    root, child 2
    root, child 3, child 3a
    

    Then you can make it a tree by executing:

    TreeMap root = new TreeMap<>();
    Scanner scanner = new Scanner(new File("input.txt"));
    while (scanner.hasNextLine()) {
      root.put(scanner.nextLine().split(", "));
    }
    

    And you will get a nice tree. It should be easy to adapt to your needs.

提交回复
热议问题