import java.util.ArrayList; import java.util.List; class Node { private List> children = new ArrayList>(); private Node parent = null; private T data = null; public Node(T data) { this.data = data; } public Node(T data, Node parent) { this.data = data; this.setParent(parent); } public List> getChildren() { return children; } public void setParent(Node parent) { parent.addChild(this); this.parent = parent; } public void addChild(T data) { Node child = new Node(data); this.children.add(child); } public void addChild(Node child) { 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; } } public class Main { public static void main(String[] args) { Node parentNode = new Node("Parent"); Node childNode1 = new Node("Child 1", parentNode); Node childNode2 = new Node("Child 2"); childNode2.setParent(parentNode); Node grandchildNode = new Node("Grandchild of parentNode. Child of childNode1", childNode1); List> childrenNodes = parentNode.getChildren(); for(Node node : childrenNodes) { System.out.println(node.getData()); } } } // Credit to https://stackoverflow.com/questions/19330731/tree-implementation-in-java-root-parents-and-children