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.

3
  • Here, for starters: stackoverflow.com/questions/3522454/java-tree-data-structure Commented Jan 16, 2012 at 4:03
  • How do I use that without swing? Commented Jan 16, 2012 at 4:09
  • There's a perfectly good example one answer down from the javax.swing answer which basically expands on Adrian's response (though I will say, Stephen C's answer has some great context). Commented Jan 16, 2012 at 4:25

5 Answers 5

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

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;
}
}

Comments

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

1 Comment

A similar option is the Node class in javax.xml.soap: 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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.