I have a Node class and I want each Node to have a list of its leaves. For this, I create an instance variable ArrayList(). When I try to add a Node to this list I get a NullPointerException: Cannot invoke "java.util.ArrayList.add(Object)" because "this.nextSibling" is null. Why is this happening?
This is my code:
public class Node {
private String name;
private Node firstChild;
private ArrayList<Node> nextSibling;
Node (String n, Node d, ArrayList<Node> r) {
this.name = n;
this.firstChild = d;
this.nextSibling = r;
}
Node() {
this("", null, null);
}
Node (String s) {
this(s, null, null);
}
Node (String s, Node p) {
this(s, p, null);
}
Node(String s, ArrayList<Node> lst) {
this(s, null, lst);
}
public void setFirstChild (Node d) {
firstChild = d;
}
public void addNextSibling (Node r) {
nextSibling.add(r);
}
public static Node parsePostfix (String s) {
if (checkForNoData(s)) {
throw new RuntimeException("Invalid input: " + s);
}
Stack<Node> nodeStack = new Stack<>();
List<String> nodeNamesCheck = new ArrayList<>();
List<String> nodeNames = getNodeNames(s);
int y = nodeNames.size() - 1;
Node root = new Node(nodeNames.get(y));
nodeStack.push(root);
nodeNamesCheck.add(nodeNames.get(y));
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == ')') {
y--;
Node firstChild = new Node(nodeNames.get(y), new ArrayList<>());
nodeNamesCheck.add(nodeNames.get(y));
nodeStack.peek().setFirstChild(firstChild);
nodeStack.push(firstChild);
} if (s.charAt(i) == ',') {
if (!nodeStack.empty())
nodeStack.pop();
y--;
Node nextSibling = new Node(nodeNames.get(y), new ArrayList<>());
nodeNamesCheck.add(nodeNames.get(y));
nodeStack.peek().addNextSibling(nextSibling);
nodeStack.push(nextSibling);
} else if (s.charAt(i) == '(') {
if (!nodeStack.empty()) {
nodeStack.pop();
}
}
}
if (nodeNames.size() != nodeNamesCheck.size() && nodeNames.size() != 1)
throw new RuntimeException("Invalid input: " + s);
return root;
}
}
The parsePostfix(String s) method takes a tree as a string and re-creates this with Nodes. An example input would be "(H,G,F)E,(D,C,)B)A".
nextSibling. To me the concept of next sibling has really nothing to do with the concept "all my leaves". What would it mean for the first entry in that array list to be a node that also has an array list? Are you really going to duplicate all sibling references in all their array lists? And how does this relate with leaves? Please clarify.