need to find all the childern and subchildern of a node in an n array tree excluding the parent whose name match a certain string. For example the hierarchy is:
root
- x(a1)
-a
-b
-x(a2)
-x(a3)
-x(a4)now when I call root.find("x") it should return a1,a2,a3,a4 when I call a1.find("x") it should return only the childern matching and not the parent i.e return only a2.
I wrote something but that looks kinda hacky. Here is what I wrote. Was thinking how I can optimize it and write some clean code
class Node {
private String name;
private ArrayList<Node> nodes;
private Node parent;
Node(String name, Node parent) {
this.name = name;
this.parent = parent;
this.nodes = new ArrayList<Node>();
}
public Node parent() {
return this.parent;
}
public String name() {
return this.name;
}
public ArrayList<Node> nodes() {
return this.nodes;
}
public Node addChild(String name) {
Node child = new Node(name, this);
this.nodes.add(child);
return child;
}
public ArrayList<Node> find(String query) {
ArrayList<Node> result = new ArrayList<Node>();
find(query,result,false);
return result;
}
public void find(String query,ArrayList<Node> result,boolean isIncluded) {
if ( name().equalsIgnoreCase( query ) && isIncluded) {
result.add(this);
}
//ArrayList<Node> resultList = new ArrayList<>();
for (Node child : this.nodes) {
child.find(query,result,true);
}
}
}
```