home5/src/Node.java

92 lines
2.8 KiB
Java

import java.util.*;
public class Node {
private String name;
private Node firstChild;
private Node nextSibling;
Node (String n, Node d, Node r) {
this.name = n;
this.firstChild = d;
this.nextSibling = r;
}
public static Node parsePostfix (String s) {
if (s.contains(",,")) {
throw new RuntimeException("double commas");
} else if (s.contains("\t")) {
throw new RuntimeException("tab char");
} else if (s.contains("()")) {
throw new RuntimeException("empty subtree");
} else if (s.contains(" ")) {
throw new RuntimeException("space");
} else if (s.contains("((") && s.contains("))")) {
throw new RuntimeException("Brackets");
} else if (s.contains(",") && !(s.contains("(") && s.contains(")"))) {
throw new RuntimeException("two roots");
}
String[] tokens = s.split("");
Stack<Node> stack = new Stack();
Node node = new Node(null, null, null);
boolean replacingRoot = false;
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i].trim();
if (token.equals("(")) {
if (replacingRoot) {
throw new RuntimeException("Trying to replace root");
}
stack.push(node);
node.firstChild = new Node(null, null, null);
node = node.firstChild;
if (tokens[i+1].trim().equals(",")) {
throw new RuntimeException("comma after node");
}
} else if (token.equals(")")) {
node = stack.pop();
if (stack.size() == 0) {
replacingRoot = true;
}
} else if (token.equals(",")) {
if (replacingRoot) {
throw new RuntimeException("Trying to replace root");
}
node.nextSibling = new Node(null, null, null);
node = node.nextSibling;
} else {
if (node.name == null) {
node.name = token;
} else {
node.name += token;
}
}
}
return node;
}
public String leftParentheticRepresentation() {
StringBuilder sb = new StringBuilder();
sb.append(this.name);
if (this.firstChild != null) {
sb.append("(");
sb.append(this.firstChild.leftParentheticRepresentation());
sb.append(")");
}
if (this.nextSibling != null) {
sb.append(",");
sb.append(this.nextSibling.leftParentheticRepresentation());
}
return sb.toString();
}
public static void main (String[] param) {
String s = "(B1,C)A";
Node t = Node.parsePostfix (s);
String v = t.leftParentheticRepresentation();
System.out.println (s + " ==> " + v); // (B1,C)A ==> A(B1,C)
}
}