Is there any standard Java library class to represent a tree in Java?
Specifically I need to represent the following:
Is there any available structure for this or do I need to create my own (if so implementation suggestions would be great).
In Java, a tree node is implemented using a class. The data inside every node can be a string, char, integer, double, or float data type. A binary tree can be implemented in two ways: A node representation and an array representation.
Insert OperationThe very first insertion creates the tree. Afterwards, whenever an element is to be inserted, first locate its proper location. Start searching from the root node, then if the data is less than the key value, search for the empty location in the left subtree and insert the data.
Tree data structure is useful on occasions where linear representation of data do not suffice, such as creating a family tree. Java provides two in-built classes, TreeSet and TreeMap, in Java Collection Framework that cater to the needs of the programmer to describe data elements in the aforesaid form.
Data structure is a method of storing and organising data to make it more useful. The data structure is not written in any programming language, such as C, C++, or Java. It is a set of methods that may be used to structure data in memory in any programming language.
Here:
public class Tree<T> { private Node<T> root; public Tree(T rootData) { root = new Node<T>(); root.data = rootData; root.children = new ArrayList<Node<T>>(); } public static class Node<T> { private T data; private Node<T> parent; private List<Node<T>> 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
.
Yet another tree structure:
public class TreeNode<T> implements Iterable<TreeNode<T>> { T data; TreeNode<T> parent; List<TreeNode<T>> children; public TreeNode(T data) { this.data = data; this.children = new LinkedList<TreeNode<T>>(); } public TreeNode<T> addChild(T child) { TreeNode<T> childNode = new TreeNode<T>(child); childNode.parent = this; this.children.add(childNode); return childNode; } // other features ... }
Sample usage:
TreeNode<String> root = new TreeNode<String>("root"); { TreeNode<String> node0 = root.addChild("node0"); TreeNode<String> node1 = root.addChild("node1"); TreeNode<String> node2 = root.addChild("node2"); { TreeNode<String> node20 = node2.addChild(null); TreeNode<String> node21 = node2.addChild("node21"); { TreeNode<String> node210 = node20.addChild("node210"); } } }
BONUS
See fully-fledged tree with:
https://github.com/gt4dev/yet-another-tree-structure
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With