Good day. The task "Create an elementary tree structure." I had difficulties with adding an element, I understand that maybe you need to recursively walk something like a tree. It is necessary to find the parent element in the tree, if it does not have such child , add the incoming child . Here root is the root of the tree.

 public boolean add(E parent, E child) { if (root.eqValue(parent)) { //если наш корень это parent if (!root.contain(child)) { //и в нем нет такого child, добавляем в него child root.add(new Node<>(child)); modCount++; return true; } } else { //если parent не корень, что делать? } return false; } 
  • Well, you need to implement the search function in the parent tree itself; then in the place where you specified the comment to refer to this function. The search algorithm is recursive: see the children of the root, if you don’t have one, see the children of the children - Dmig
  • I understand in theory what to do, I don’t know how to arrange it in the code, because I end up with what I’m going to on the outermost branch on the left, then exit the loop. But I need to check all the branches - Dmitry

1 answer 1

 private Boolean add(Node node, E parent, E child) { if (node.eqValue(parent)) { // если наш узел это parent if (!node.contain(child)) { // и в нем нет такого child, добавляем в него child node.add(new Node<>(child)); modCount++; return true; // Если добавили - вернем true } else return false; // Если нашли, но не добавили - вернем false } else { for (Node childNode : node) { // Цикл по всем потомкам Boolean res = add(childNode, parent, child); if (res != null) // Если узел нашли return res; // то выходим } // Если попали сюда, то ничего не нашли return null; } } public boolean add(E parent, E child) { // Пытаемся добавить в корень, а там как пойдет Boolean res = add(root, parent, child); return res != null; // Если элемент был найден, вернем true }