Advertisement
valiamaximova1

Tree

Mar 27th, 2020
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.95 KB | None | 0 0
  1. package com.javagists.examples.tree;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. public class Tree {
  7.     public static void main(String[] args) {
  8.         Tree.Node<String> root = createTree();
  9.         printTree(root, "*");
  10.     }
  11.  
  12.  
  13.     private static Node<String> createTree() {
  14.         Tree.Node<String> root = new Tree.Node<>("Пенка и Велислав");
  15.  
  16.         Tree.Node<String> father = root.addChild(new Tree.Node<String>("Валентин"));
  17.        
  18.         Tree.Node<String> sister = father.addChild(new Tree.Node<String>("Олимпия"));
  19.         Tree.Node<String> me = father.addChild(new Tree.Node<String>("Валентина"));
  20.  
  21.  
  22.  
  23.         return root;
  24.     }
  25.  
  26.  
  27.     private static <T> void printTree(Tree.Node<T> node, String appender) {
  28.         System.out.println(appender + node.getData());
  29.         node.getChildren().forEach(each -> printTree(each, appender + appender));
  30.     }
  31.  
  32.     static class Node<T> {
  33.  
  34.         private T data = null;
  35.  
  36.         private List<Tree.Node<T>> children = new ArrayList<>();
  37.  
  38.         private Tree.Node<T> parent = null;
  39.  
  40.         public Node(T data) {
  41.             this.data = data;
  42.         }
  43.  
  44.         public Tree.Node<T> addChild(Tree.Node<T> child) {
  45.             child.setParent(this);
  46.             this.children.add(child);
  47.             return child;
  48.         }
  49.  
  50.         public void addChildren(List<Tree.Node<T>> children) {
  51.             children.forEach(each -> each.setParent(this));
  52.             this.children.addAll(children);
  53.         }
  54.  
  55.         public List<Tree.Node<T>> getChildren() {
  56.             return children;
  57.         }
  58.  
  59.         public T getData() {
  60.             return data;
  61.         }
  62.  
  63.         public void setData(T data) {
  64.             this.data = data;
  65.         }
  66.  
  67.         private void setParent(Tree.Node<T> parent) {
  68.             this.parent = parent;
  69.         }
  70.  
  71.         public Tree.Node<T> getParent() {
  72.             return parent;
  73.         }
  74.  
  75.  
  76.  
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement