Advertisement
Mariyan17320

Iliev's homework Mariyan17320

Mar 26th, 2020
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. class Node<T> {
  5.     private T data = null;
  6.  
  7.     private List<Node<T>> children = new ArrayList<>();
  8.  
  9.     private Node<T> parent = null;
  10.  
  11.     public Node(T data) {
  12.         this.data = data;
  13.     }
  14.     public Node<T> addChild(Node<T> child) {
  15.         child.setParent(this);
  16.         this.children.add(child);
  17.         return child;
  18.     }
  19.     public void addChildren(List<Node<T>> children) {
  20.         children.forEach(each -> each.setParent(this));
  21.         this.children.addAll(children);
  22.     }
  23.     public List<Node<T>> getChildren() {
  24.         return children;
  25.     }
  26.     public T getData() {
  27.         return data;
  28.     }
  29.     public void setData(T data) {
  30.         this.data = data;
  31.     }
  32.     private void setParent(Node<T> parent) {
  33.         this.parent = parent;
  34.     }
  35.     public Node<T> getParent() {
  36.         return parent;
  37.     }
  38. }
  39. class TreeExample {
  40.     public static void main(String[] args) {
  41.         Node<String> root = createTree();
  42.         printTree(root, " ");
  43.     }
  44.     private static Node<String> createTree() {
  45.         Node<String> root = new Node<>("Mariyan");
  46.         Node<String> node1 = root.addChild(new Node<String>("Krasimir"));
  47.         Node<String> node11 = node1.addChild(new Node<String>("Angel"));
  48.         Node<String> node12 = node1.addChild(new Node<String>("Totka"));
  49.         Node<String> node2 = root.addChild(new Node<String>("Trayana"));
  50.         Node<String> node21 = node2.addChild(new Node<String>("Hristo"));
  51.         Node<String> node211 = node2.addChild(new Node<String>("Mariika"));
  52.         return root;
  53.     }
  54.     private static <T> void printTree(Node<T> node, String appender) {
  55.         System.out.println(appender + node.getData());
  56.         node.getChildren().forEach(each -> printTree(each, appender + appender));
  57.     }
  58. }
  59.  
  60. //Mariyan17320
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement