Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- class Node<T> {
- private T data = null;
- private List<Node<T>> children = new ArrayList<>();
- private Node<T> parent = null;
- public Node(T data) {
- this.data = data;
- }
- public Node<T> addChild(Node<T> child) {
- child.setParent(this);
- this.children.add(child);
- return child;
- }
- public void addChildren(List<Node<T>> children) {
- children.forEach(each -> each.setParent(this));
- this.children.addAll(children);
- }
- public List<Node<T>> getChildren() {
- return children;
- }
- public T getData() {
- return data;
- }
- public void setData(T data) {
- this.data = data;
- }
- private void setParent(Node<T> parent) {
- this.parent = parent;
- }
- public Node<T> getParent() {
- return parent;
- }
- }
- class TreeExample {
- public static void main(String[] args) {
- Node<String> root = createTree();
- printTree(root, " ");
- }
- private static Node<String> createTree() {
- Node<String> root = new Node<>("Mariyan");
- Node<String> node1 = root.addChild(new Node<String>("Krasimir"));
- Node<String> node11 = node1.addChild(new Node<String>("Angel"));
- Node<String> node12 = node1.addChild(new Node<String>("Totka"));
- Node<String> node2 = root.addChild(new Node<String>("Trayana"));
- Node<String> node21 = node2.addChild(new Node<String>("Hristo"));
- Node<String> node211 = node2.addChild(new Node<String>("Mariika"));
- return root;
- }
- private static <T> void printTree(Node<T> node, String appender) {
- System.out.println(appender + node.getData());
- node.getChildren().forEach(each -> printTree(each, appender + appender));
- }
- }
- //Mariyan17320
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement