How to implement a tree data-structure in Java?

A tree is a data structure that consists of nodes arranged in a hierarchy. Each node has a value and may have zero or more child nodes. The top node in a tree is called the root node.

Here is an example of how you could implement a tree data structure in Java:

public class TreeNode {
  private int value;
  private List<TreeNode> children;

  public TreeNode(int value) {
    this.value = value;
    this.children = new ArrayList<>();

  public void addChild(TreeNode child) {

  public int getValue() {
    return value;

  public List<TreeNode> getChildren() {
    return children;

This TreeNode class represents a single node in the tree, with a value and a list of child nodes. It has methods for adding children and accessing the value and children of the node.

To create a tree, you would create a root node and then add child nodes to it:

TreeNode root = new TreeNode(1);
root.addChild(new TreeNode(2));
root.addChild(new TreeNode(3));
root.addChild(new TreeNode(4));

This would create a tree with a root node that has three child nodes. The child nodes would have values 2, 3, and 4.

You can traverse the tree by starting at the root node and visiting each child recursively. For example, you could write a method to print out the values of all the nodes in the tree like this:

public void printTree(TreeNode node) {
  for (TreeNode child : node.getChildren()) {

This method would print out the value of the current node, and then recursively call itself for each of the children of the node.

There are many other ways you could implement a tree data structure in Java, depending on your specific needs. This is just one example.