简体   繁体   中英

Display tree hierarchy with their values in Java

I have to create a tree structure with a parent node having many children, and each child can also have their children. Each node will be identified by their unique id and name.

So when I enter any id from the hierarchy, all node-ids and their child node-ids with their names should get printed. How can I achieve this(any sample code would help) and which collection should be used from collection framework or do I have to use plain data structures in Java?

One possible way is to create your own tree structure (node with children) and wrap it into another structure that tracks nodes' ids. Something like that:

public class Tree<I, A> {
    private final HashMap<I, Node<I, A>> map = new HashMap<>();
    private final Node<I, A> root;

    public Tree(I id, A value) {
        root = new Node<>(id, value);
        map.put(id, root);
    }

    public void addChild(I parentId, I id, A value) {
        Node<I, A> parent = map.get(parentId);
        Node<I, A> child = new Node<>(id, value);
        parent.children.add(child);
        map.put(id, child);
    }

    public A getById(I id) {
        return map.get(id).value;
    }

    public String subtreeToString(I id) {
        return map.get(id).toString();
    }

    private static class Node<I, A> {
        private final I id;
        private final A value;
        private final ArrayList<Node<I, A>> children = new ArrayList<>();

        private Node(I id, A value) {
            this.id = id;
            this.value = value;
        }

        private void print(int depth, PrintWriter pw) {
            for (int i = 0; i < depth; i++) {
                pw.print("\t");
            }
            pw.println("[" + id + ", " + value + "]");
            for (Node<I, A> child : children) {
                child.print(depth + 1, pw);
            }
        }

        @Override
        public String toString() {
            StringWriter writer = new StringWriter();
            print(0, new PrintWriter(writer));
            return writer.toString();
        }
    }
}

Usage:

Tree<Integer, String> tree = new Tree<>(1, "Bob");

tree.addChild(1, 2, "John");
tree.addChild(1, 3, "James");
tree.addChild(2, 4, "David");
tree.addChild(2, 5, "Alice");

System.out.println(tree.subtreeToString(1));
System.out.println(tree.subtreeToString(2));

Output:

[1, Bob]
    [2, John]
        [4, David]
        [5, Alice]
    [3, James]

[2, John]
    [4, David]
    [5, Alice]

您将必须制作自己的树结构,并且在打印时,只需在父节点上调用toString(),然后从该节点上在子节点上调用toString()等。

There might be some structure ready for the task, but on the other hand: this task is very straightforward to do yourself – just do a recursive in-order walk down the tree:

  1. Start at the root node
  2. If there is a left node: enter it and go to 2.
  3. Else: print the content.
  4. If there is a right node: enter it and go to 2.
  5. Else: return

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM