Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.javagists.examples.tree;
- import java.util.ArrayList;
- import java.util.List;
- public class Tree {
- public static void main(String[] args) {
- Tree.Node<String> root = createTree();
- printTree(root, "*");
- }
- private static Node<String> createTree() {
- Tree.Node<String> root = new Tree.Node<>("Пенка и Велислав");
- Tree.Node<String> father = root.addChild(new Tree.Node<String>("Валентин"));
- Tree.Node<String> sister = father.addChild(new Tree.Node<String>("Олимпия"));
- Tree.Node<String> me = father.addChild(new Tree.Node<String>("Валентина"));
- return root;
- }
- private static <T> void printTree(Tree.Node<T> node, String appender) {
- System.out.println(appender + node.getData());
- node.getChildren().forEach(each -> printTree(each, appender + appender));
- }
- static class Node<T> {
- private T data = null;
- private List<Tree.Node<T>> children = new ArrayList<>();
- private Tree.Node<T> parent = null;
- public Node(T data) {
- this.data = data;
- }
- public Tree.Node<T> addChild(Tree.Node<T> child) {
- child.setParent(this);
- this.children.add(child);
- return child;
- }
- public void addChildren(List<Tree.Node<T>> children) {
- children.forEach(each -> each.setParent(this));
- this.children.addAll(children);
- }
- public List<Tree.Node<T>> getChildren() {
- return children;
- }
- public T getData() {
- return data;
- }
- public void setData(T data) {
- this.data = data;
- }
- private void setParent(Tree.Node<T> parent) {
- this.parent = parent;
- }
- public Tree.Node<T> getParent() {
- return parent;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement