Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class TreeImplementationDFS {
- public static void main(String[] args) {
- Node<String> root = createTree();
- printTree(root, " ");
- }
- private static Node<String> createTree() {
- Node<String> root = new Node<>("Роза и Иван");
- Node<String> Father = root.addChild(new Node<String>("Атанас"));
- Node<String> Aunt1 = root.addChild(new Node<String>("Стефка"));
- Node<String> Aunt2 = root.addChild(new Node<String>("Надка"));
- Node<String> Brother = Father.addChild(new Node<String>("Росен"));
- Node<String> Sister = Father.addChild(new Node<String>("Вяра"));
- Node<String> Aunt1Cousin1 = Aunt1.addChild(new Node<String>("Иван"));
- Node<String> Aunt2Cousin1 = Aunt2.addChild(new Node<String>("Ивайло"));
- Node<String> Aunt2Cousin2 = Aunt2.addChild(new Node<String>("Веселин"));
- Node<String> Aunt2Cousin1Child1 = Aunt2Cousin1.addChild(new Node<String>("Преслава"));
- Node<String> Aunt2Cousin1Child2 = Aunt2Cousin1.addChild(new Node<String>("Радостин"));
- Node<String> Aunt2Cousin2Child1 = Aunt2Cousin2.addChild(new Node<String>("Теодора"));
- Node<String> Aunt2Cousin2Child2 = Aunt2Cousin2.addChild(new Node<String>("Христяна"));
- Node<String> Aunt2Cousin2Child3 = Aunt2Cousin2.addChild(new Node<String>("Никол"));
- 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));
- }
- }
- 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;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment