1

How can I represent a tree structure like below, in java?

    "root"
     |  |
"leaf1" "leaf2"
         |   |
    "leaf3" "leaf4"
       |
    "leaf5"

Are there any built-in or custom classes anyone can refer me to?

EDIT: I need to be able to easily traverse through nodes.

user908683
  • 267
  • 2
  • 3
  • 7

5 Answers5

3

There is no generic tree type in the Java class libraries, or in either Guava or Apache Commons Collections.

The easiest solution is to implement the tree type yourself to do exactly what you require. The core functionality of a tree is trivial ... modulo that the details depend heavily on what the tree needs to contain and how your use-case requires it to behave.

(If you want to understand why there is no generic tree type, try to get your head around the discussion on this Guava issue - http://code.google.com/p/guava-libraries/issues/detail?id=174)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

Try this [very general though]:

public class Tree {
private Node root;

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

private class Node {
    private String data;
    private Node parent;
    private List<Node> children;
}
}
damned
  • 935
  • 2
  • 19
  • 35
1

It might not be part of the Collections API, but Swing's JTree TreeModel is certainly a generic tree implementation: https://docs.oracle.com/javase/7/docs/api/javax/swing/tree/TreeModel.html

Lenny Markus
  • 3,398
  • 2
  • 24
  • 30
  • A similar option is the Node class in javax.xml.soap: https://docs.oracle.com/javase/8/docs/api/javax/xml/soap/Node.html It's original purpose seems to be DOM object parsing, but should work well in this situation. – Adam Howell Jan 23 '19 at 21:24
1

Following is simple binary tree, that would solve your purpose.

http://www.java2s.com/Code/Java/Collections-Data-Structure/BinaryTree.htm

Rajendran T
  • 1,513
  • 10
  • 15
0

Just make your own Node class:

Node {
 T value;
 Node left;
 Node right;
}

For a more complex implementation see Java's N-ary tree DefaultMutableTreeNode

Adrian
  • 5,603
  • 8
  • 53
  • 85