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.

Answer from jjnguy on Stack Overflow
Top answer
1 of 16
338

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.

2 of 16
145

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:

  • iterator
  • searching
  • Java/C#

https://github.com/gt4dev/yet-another-tree-structure

🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › javax › swing › tree › TreeNode.html
TreeNode (Java Platform SE 8 )
July 21, 2026 - Returns the parent TreeNode of the receiver. ... Returns the index of node in the receivers children. If the receiver does not contain node, -1 will be returned. ... Returns true if the receiver allows children. ... Returns true if the receiver is a leaf. ... Returns the children of the receiver as an Enumeration. ... Java™ Platform Standard Ed.
Discussions

How to implement a tree data-structure in Java?
Implementing a tree data structure in Java involves defining the structure of a tree node and providing methods to manipulate the tree. Below is a basic implementation of a binary tree, which is a common type of tree data structure. In a binary tree, each node has at most two children, referred to as the left child and the right child. ... The tree node class ... More on designgurus.io
🌐 designgurus.io
1
10
August 1, 2024
Class structure: How should a binary tree and it's node class be implemented in Java in terms of class files? - Software Engineering Stack Exchange
In implementing a binary tree in Java, should the node class be a separate class file independent of the BinaryTreeclass, or should it be a default class in the same class file as the BinaryTree cl... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
May 7, 2019
Tree implementation in Java (root, parents and children) - Stack Overflow
Solvable by nixing the parent and putting it in a separate map of nodes to parents if needed. 2018-06-19T18:01:47.39Z+00:00 ... Save this answer. ... Show activity on this post. Here is my implementation in java for your requirement. In the treeNode class i used generic array to store the tree data. More on stackoverflow.com
🌐 stackoverflow.com
[Java] Trying to create a binary search tree with java and unsure how to create nodes for it. Am i making the nodes like linked-lists?
Could just make a node class with left and right children, both of which are nodes. A node should also have a field to determine the key of the node you're looking at. I'm assuming you know how to make classes, btw More on reddit.com
🌐 r/learnprogramming
17
2
March 17, 2019
🌐
GeeksforGeeks
geeksforgeeks.org › java › implementing-a-binary-tree-in-java
Implementing a Binary Tree in Java - GeeksforGeeks
May 15, 2024 - The root node of the binary tree is 8. The left child of the root has value 3 and it children are 1 and 6, and 6 has 2 children i.e. 4 and 7. The right child of the root has 10 and its children are 13 and 14. 1, 4, 7, 13 and 14 are leaf nodes which are without any children. ... // Node Class class Node { int key; Node left, right; public Node(int item) { key = item; left = right = null; } } // BinaryTree Class public class BinaryTree { Node root; public BinaryTree() { root = null; } // Method to insert a new node with given key public void insert(int key) { root = insertRec(root, key); } // A
🌐
Codecademy
codecademy.com › learn › nonlinear-data-structures-java › modules › trees-java › cheatsheet
Nonlinear Data Structures: Trees Cheatsheet | Codecademy
The .breadthFirstTraversal() method in the Tree class should print the breadth first traversal of the tree. It takes nothing and returns nothing. To implement this, we use a Queue data structure to maintain the order of children added. ... Learn about the computer science concepts of data structures and algorithms and build implementations of each from scratch in modern Java.
🌐
Medium
medium.com › @YodgorbekKomilo › a-comprehensive-guide-to-tree-data-structures-in-java-from-beginner-to-advanced-2232d0902208
A Comprehensive Guide to Tree Data Structures in Java: From Beginner to Advanced | by Yodgorbek Komilov | Medium
January 16, 2025 - A Binary Search Tree (BST) is a binary tree where each node has a value greater than all the values in its left subtree and less than those in its right subtree. This property makes BSTs suitable for efficient searching, insertion, and deletion operations. class BST { class Node { int key; Node left, right; public Node(int item) { key = item; left = right = null; } } Node root; public BST() { root = null; } void insert(int key) { root = insertRec(root, key); } Node insertRec(Node root, int key) { if (root == null) { root = new Node(key); return root; } if (key < root.key) root.left = insertRec
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › javax › swing › tree › TreeNode.html
TreeNode (Java Platform SE 7 )
Returns the parent TreeNode of the receiver. ... Returns the index of node in the receivers children. If the receiver does not contain node, -1 will be returned. ... Returns true if the receiver allows children. ... Returns true if the receiver is a leaf. ... Returns the children of the receiver as an Enumeration. ... Java™ Platform Standard Ed.
🌐
Java Code Gists
javagists.com › home › java tree data structure
Java Tree Data Structure - Java Code Gists
January 20, 2018 - Root node doesn’t have a parent but has children. We will create a class Node that would represent each node of the tree. Node class has a data attribute which is defined as a generic type.
Find elsewhere
🌐
Duke
www2.cs.duke.edu › csed › ap › subset › doc › ap › TreeNode.html
TreeNode (Advanced Placement Computer Science Java Subset Specification)
The class for nodes in a binary tree that will be used and tested on the Advanced Placement Computer Science exam.
🌐
Medium
medium.com › @YodgorbekKomilo › understanding-tree-data-structures-in-java-4d230ab266a5
Understanding Tree Data Structures in Java | by Yodgorbek Komilov | Medium
August 19, 2024 - Root Node: The topmost node of a tree, which has no parent. Child Node: A node directly connected to another node when moving away from the root. Parent Node: A node that has one or more child nodes.
🌐
University of Texas
cs.utexas.edu › ~scottm › cs314 › javacode › A10_Huffman › doc › TreeNode.html
TreeNode
java.lang.Object · TreeNode · All Implemented Interfaces: Comparable<TreeNode> public class TreeNode extends Object implements Comparable<TreeNode> Utility binary-tree (Huffman tree) node for Huffman coding. This is a simple, standard binary-tree node implementing the comparable interface based on frequency.
🌐
University of Iowa
homepage.cs.uiowa.edu › ~sriram › 21 › fall08 › code › tree.java
tree.java
// tree.java // demonstrates binary tree // to run this program: C>java TreeApp import java.io.*; import java.util.*; // for Stack class //////////////////////////////////////////////////////////////// class Node { public int iData; // data item (key) public double dData; // data item public Node leftChild; // this node's left child public Node rightChild; // this node's right child public void displayNode() // display ourself { System.out.print('{'); System.out.print(iData); System.out.print(", "); System.out.print(dData); System.out.print("} "); } } // end class Node ////////////////////////
🌐
Java Challengers
javachallengers.com › home › tree data structure with java
Tree Data Structure with Java
December 12, 2022 - The leaf node is the node that doesn’t have any children and is not the root node. In algorithms, you will see a lot of the nomenclature height. Height in trees is the number of nodes from the highest branch to the root node.
Top answer
1 of 8
50
import java.util.ArrayList;
import java.util.List;

public class Node<T> {
    private List<Node<T>> children = new ArrayList<Node<T>>();
    private Node<T> parent = null;
    private T data = null;

    public Node(T data) {
        this.data = data;
    }

    public Node(T data, Node<T> parent) {
        this.data = data;
        this.parent = parent;
    }

    public List<Node<T>> getChildren() {
        return children;
    }

    public void setParent(Node<T> parent) {
        parent.addChild(this);
        this.parent = parent;
    }

    public void addChild(T data) {
        Node<T> child = new Node<T>(data);
        child.setParent(this);
        this.children.add(child);
    }

    public void addChild(Node<T> child) {
        child.setParent(this);
        this.children.add(child);
    }

    public T getData() {
        return this.data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public boolean isRoot() {
        return (this.parent == null);
    }

    public boolean isLeaf() {
        return this.children.size() == 0;
    }

    public void removeParent() {
        this.parent = null;
    }
}

Example:

import java.util.List;

Node<String> parentNode = new Node<String>("Parent"); 
Node<String> childNode1 = new Node<String>("Child 1", parentNode);
Node<String> childNode2 = new Node<String>("Child 2");     

childNode2.setParent(parentNode); 

Node<String> grandchildNode = new Node<String>("Grandchild of parentNode. Child of childNode1", childNode1); 
List<Node<String>> childrenNodes = parentNode.getChildren();
2 of 8
35

Accepted answer throws a java.lang.StackOverflowError when calling the setParent or addChild methods.

Here's a slightly simpler implementation without those bugs:

public class MyTreeNode<T>{
    private T data = null;
    private List<MyTreeNode> children = new ArrayList<>();
    private MyTreeNode parent = null;

    public MyTreeNode(T data) {
        this.data = data;
    }

    public void addChild(MyTreeNode child) {
        child.setParent(this);
        this.children.add(child);
    }

    public void addChild(T data) {
        MyTreeNode<T> newChild = new MyTreeNode<>(data);
        this.addChild(newChild);
    }

    public void addChildren(List<MyTreeNode> children) {
        for(MyTreeNode t : children) {
            t.setParent(this);
        }
        this.children.addAll(children);
    }

    public List<MyTreeNode> getChildren() {
        return children;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    private void setParent(MyTreeNode parent) {
        this.parent = parent;
    }

    public MyTreeNode getParent() {
        return parent;
    }
}

Some examples:

MyTreeNode<String> root = new MyTreeNode<>("Root");

MyTreeNode<String> child1 = new MyTreeNode<>("Child1");
child1.addChild("Grandchild1");
child1.addChild("Grandchild2");

MyTreeNode<String> child2 = new MyTreeNode<>("Child2");
child2.addChild("Grandchild3");

root.addChild(child1);
root.addChild(child2);
root.addChild("Child3");

root.addChildren(Arrays.asList(
        new MyTreeNode<>("Child4"),
        new MyTreeNode<>("Child5"),
        new MyTreeNode<>("Child6")
));

for(MyTreeNode node : root.getChildren()) {
    System.out.println(node.getData());
}
🌐
Oracle
docs.oracle.com › javase › tutorial › uiswing › components › tree.html
How to Use Trees (The Java™ Tutorials > Creating a GUI With Swing > Using Swing Components)
To summarize, you can create a tree by invoking the JTree constructor, specifying the class that implements TreeNode as an argument. You should probably put the tree inside a scroll pane, so that the tree would not take up too much space. You do not have to do anything to make the tree nodes expand and collapse in response to user clicks.
🌐
Baeldung
baeldung.com › home › algorithms › implementing a binary tree in java
Implementing a Binary Tree in Java | Baeldung
May 11, 2024 - Here’s a visual representation of this type of binary tree: For the implementation, we’ll use an auxiliary Node class that will store int values, and keep a reference to each child:
🌐
Educative
educative.io › blog › data-structures-trees-java
Data structures 101: A deep dive into trees with Java
But, how does that all look in code? To build a tree in Java, for example, we start with the root node.