N
nastya2018
Ребята я создала две рекурсии PrintCatalog и Printtree (как их объединить в одной новой рекурсии printTree)
Код:
import java.util.*;
public class TreePrint {
public static void main(String[] args) {
Tree<String> rootFolder = new Tree<>("RootFolder");
Node<String> video = rootFolder.addChild( "Video" );
Node<String> music = rootFolder.addChild( "Music" );
Node<String> picture = rootFolder.addChild( "Picture" );
video.addChild( "Terminator" );
video.addChild( "Die Hard" );
video.addChild( "Rocky" );
music.addChild( "Eminem" );
picture.addChild( "Picasso" );
printCatalog(rootFolder);
}
private static <T> void printTree(Node<T> node) {
???????????????????????????????????????????
????????????????????????????????????????
}
private static <T> void printCatalog(Tree<T> rootFolder) {
printNode( rootFolder, 0 );
List<Node<T>> kids = rootFolder.getChildren();
printTree(kids, 1 );
}
private static <T> void printTree(List<Node<T>> kids, int level ) {
if (kids.isEmpty()) {
return;
}
for (Node<T> kid : kids) {
printNode(kid, level );
printTree(kid.getChildren(), level+1 );
}
}
private static <T> void printNode(Node<T> kid, int level ) {
for ( int i=0; i<level; i++ ) {
System.out.print( " " );
}
System.out.println(kid.getData());
}
}
-----------------------
import java.util.List;
public class Tree<T> extends Node<T> {
public Tree(T data) {
super(data, null);
}
}
----------------------------
import java.util.ArrayList;
import java.util.List;
public class Node<T> {
private T data;
private final List<Node<T>> children = new ArrayList<>();
private final Node<T> parent;
public Node(T data, Node<T> parent) {
this.data = data;
this.parent = parent;
}
public void addChild(Node<T> node) {
children.add(node);
}
public Node<T> addChild(T nodeData) {
Node<T> newNode = new Node<T>( nodeData, this );
children.add( newNode );
return newNode;
}
public List<Node<T>> iterate() {
return children;
}
public void remove(Node<T> node) {
children.remove(node);
}
public List<Node<T>> getChildren() {
return children;
}
public Node getParent() {
return parent;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}