Мне нужно создать дерево, и найти сумму которая ровняется умножению каждой вершины дерева на глубину.У меня есть два класса Node и Main. В классе Node я объявляю основные функции для роботы с деревом, в классе Main функцией readChildren заполняю дерево, но не знаю как найти глубину самого дерева (дерево не двоичное)
public class Main {
static Node<Integer> theNode;
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter root value: ");
Node<Integer> root = new Node<>(Integer.parseInt(reader.readLine()));
System.out.println("Enter childs with coma separator: ");
System.out.println("For root element: ");
readChildren(root);
}
public static void readChildren(Node<Integer> child) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter children for " + child.getData() + ": ");
String children = reader.readLine();
if (children.isEmpty())
return;
String charr[] = children.split(",");
int i = 0;
for (String ch : charr) {
child.addChild(Integer.parseInt(ch));
readChildren(child.getChildren().get(i++));
}
}
}
import java.util.ArrayList;
import java.util.List;
public class Node<T> {
private List<Node<T>> children = new ArrayList<Node<T>>();
private Node<T> parent = null;
private T data = null;
public Node(T data) {
this.data = data;
}
public Node(T data, Node<T> parent) {
this.data = data;
this.parent = parent;
}
public List<Node<T>> getChildren() {
return children;
}
public void setParent(Node<T> parent) {
// parent.addChild(this);
this.parent = parent;
}
public void addChild(T data) {
Node<T> child = new Node<T>(data);
child.setParent(this);
this.children.add(child);
}
public void addChild(Node<T> child) {
child.setParent(this);
this.children.add(child);
}
public int getChildrenCount() {
return this.getChildren().size();
}
public T getData() {
return this.data;
}
public void setData(T data) {
this.data = data;
}
public boolean isRoot() {
return (this.parent == null);
}
public boolean isLeaf() {
if (this.children.size() == 0)
return true;
else
return false;
}
public void removeParent() {
this.parent = null;
}
}
Код не рабочий, я для примера привожу
public int getTreeHight(){
return getTreeHightRecurs(root);
}
private int getTreeHightRecurs(Node root){
if (root.getChildrens()=null) return 1;
List<Integer> hihgts = new LinkedList<>();
for (Node node:root.getChildrens()){
int hight = getTreeHightRecurs(node);
hihgts.add(hight);
}
return Collections.max(hihgts);
}
С java8 Stream вообще будет 2 строки, только я пока не готов его написать
написал свою функцию для поиска глубины, может кому-то понадобится
public static int getTreeHightRecurs(Node<Integer> root) {
int deep = 0;
for (Node<Integer> node :root.getChildren())
deep = Integer.max(deep, getTreeHightRecurs(node));
return deep+1;
}
Современные инструменты для криптотрейдинга: как технологии помогают принимать решения
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости