public class Expression {
/**
* @param args
*/
public static void main(String[] args) {
BTreeNode node = build(expression, new java.util.Stack<BTreeNode>(), new BTreeNode(null));
System.out.println(node.toString());
}
//private static String expression = "1+(2*(2+3)+3)*(9-3)+1+1";
//private static String expression = "(1+(2*3))*(9-3)+1+1";
private static String expression = "(((a>b)&(c<d))|(e<f)&(f=g))&((h>i)||(m<n))";
private static int start= 0;
public static BTreeNode build(String expression, java.util.Stack<BTreeNode> stack, BTreeNode node){
while (start < expression.length()) {
char c = expression.charAt(start++);
switch (c) {
case '>':
case '<':
case '|':
case '&':
case '=':
node.setValue(c);
break;
case '(':
stack.push(node);
node = build(expression, stack, new BTreeNode(null));
break;
case ')':
BTreeNode lastNode = stack.pop();
//TODO Check NULL
if (lastNode.hasLeft()) {
lastNode.setRight(node.getLeft());
BTreeNode root = new BTreeNode(null);
root.setLeft(lastNode);
node = root;
} else {
lastNode.setLeft(node.getLeft());
node = lastNode;
}
return node;
default:
BTreeNode valueNode = new BTreeNode(c);
if (node.hasLeft()) {
node.setRight(valueNode);
BTreeNode root = new BTreeNode(null);
root.setLeft(node);
node = root;
} else {
node.setLeft(valueNode);
}
}
}
if (node.getValue() == null && !node.hasRight()) {
node = node.getLeft();
}
return node;
}
}
----------------------------------------
public class BTreeNode {
private Object value;
private BTreeNode left;
private BTreeNode right;
public BTreeNode(Object value) {
super();
this.value = value;
}
public Object getValue() {
return value;
}
public BTreeNode getLeft() {
return left;
}
public BTreeNode getRight() {
return right;
}
public void setLeft(BTreeNode left) {
this.left = left;
}
public void setValue(Object value) {
this.value = value;
}
public void setRight(BTreeNode right) {
this.right = right;
}
public boolean isFinalData(){
return !Expression2.operatorSet.contains(this.value)?true:false;
}
public boolean isLeaf() {
return this.left == null && this.right == null;
}
public boolean hasLeft(){
return this.left != null;
}
public boolean hasRight(){
return this.right != null;
}
public String toString(){
if (this.isLeaf()) {
return String.valueOf(this.value);
} else {
System.out.println("L:" + this.getLeft().toString());
System.out.println("R:" + this.getLeft().toString());
return "(" + this.getLeft().toString() + this.value + this.getRight().toString() + ")";
}
}
}