| |
14. 67. 5. 表达式树 |
|
import java.util.Enumeration;
import java.util.Stack;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class ExpressionTree extends JFrame {
public ExpressionTree() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("+");
root.add(new DefaultMutableTreeNode(new Integer(3)));
DefaultMutableTreeNode node = new DefaultMutableTreeNode("*");
node.add(new DefaultMutableTreeNode(new Integer(4)));
node.add(new DefaultMutableTreeNode(new Integer(5)));
root.add(node);
JTree tree = new JTree(root);
getContentPane().add(tree);
pack();
setVisible(true);
Stack stack = new Stack();
Enumeration e = root.postorderEnumeration();
while (e.hasMoreElements()) {
DefaultMutableTreeNode node1 = (DefaultMutableTreeNode) (e.nextElement());
Object obj = node1.getUserObject();
if (obj instanceof Integer) {
stack.push(obj);
} else {
String operator = (String) obj;
Integer v1 = (Integer) stack.pop();
Integer v2 = (Integer) stack.pop();
if (operator.equals("+")) {
stack.push(new Integer(v2.intValue() + v1.intValue()));
} else {
stack.push(new Integer(v2.intValue() * v1.intValue()));
}
}
}
System.out.println(stack.pop());
}
public static void main(String[] args) {
ExpressionTree t = new ExpressionTree();
}
}
|
|
|