Expression Tree

  1. /**
  2.  * filename: ExpressionTree.java
  3.  * package: 
  4.  * author: Nick Ma
  5.  * email: nick.ma85@yahoo.com
  6.  * date: Nov 1, 2008
  7.  * description: this class implements an expression tree extended from binary tree.
  8.  */
  9. import  java.util.*;
  10. public   class  ExpressionTree  extends  BinaryTree {
  11.          // Data Field
  12.         
  13.          /** the operators */
  14.          private   static   final  String OPERATORS =  "+-*/" ;
  15.         
  16.          /** the original infix expression */
  17.          private  String originalExp;
  18.          /**
  19.          * description: the constructor with fields to build an expression tree from infix
  20.          * @param originalExp - infix exp
  21.          */
  22.          public  ExpressionTree(String originalExp) {
  23.                  this .originalExp = originalExp;
  24.                 
  25.                 InfixToPostfixConvertor pc =  new  InfixToPostfixConvertor();
  26.                  try  {
  27.                          // convert the original infix exp to postfix
  28.                         StringTokenizer st =  new  StringTokenizer(pc.convert(originalExp));
  29.                          // stack to save temp tree nodes
  30.                         Stack<TreeNode> treeStack =  new  Stack<TreeNode>();
  31.                         
  32.                          while (st.hasMoreTokens()) {
  33.                                  // iterator the tokens
  34.                                 String nextToken = st.nextToken();
  35.                                  char  firstChar = nextToken.charAt( 0 );
  36.                                  // determine if it is an operand
  37.                                  if (Character.isJavaIdentifierStart(firstChar)
  38.                                                 || Character.isDigit(firstChar)){
  39.                                         treeStack.push( new  TreeNode(nextToken));
  40.                                 }  else   if (isOperator(firstChar)) {
  41.                                          // pop two operands
  42.                                         TreeNode right = treeStack.pop();
  43.                                         TreeNode left = treeStack.pop();
  44.                                         
  45.                                          //create a new tree to push
  46.                                         treeStack.push( new  TreeNode(nextToken, left, right));
  47.                                 }  else  {
  48.                                          throw   new  SyntaxErrorException( "syntax error!" );
  49.                                 }
  50.                         }
  51.                         
  52.                          // determine if the tree stack just has one tree
  53.                          if (treeStack.size() !=  1 ) {
  54.                                  throw   new  SyntaxErrorException( "syntax error" );
  55.                         }
  56.                         
  57.                          // let the only tree node popped from the tree stack be the root
  58.                          this .root = treeStack.pop();
  59.                         
  60.                          // determine if the tree stack is empty
  61.                          if (!treeStack.isEmpty()) {
  62.                                  throw   new  SyntaxErrorException( "syntax error" );
  63.                         }
  64.                 }  catch (Exception e) {
  65.                         e.printStackTrace();
  66.                 }
  67.         }
  68.         
  69.          /**
  70.          * description: print prefix exp from this tree
  71.          */
  72.          public   void  prefix(TreeNode node) {
  73.                  if (node ==  null ) {
  74.                          return ;
  75.                 }  else  {
  76.                         System.out.print((String)node.getData());
  77.                         prefix(node.getLeft());
  78.                         prefix(node.getRight());
  79.                 }
  80.         }
  81.         
  82.          /**
  83.          * description: print infix exp from this tree
  84.          */
  85.          public   void  infix(TreeNode node) {
  86.                  if (node ==  null ) {
  87.                          return ;
  88.                 }  else  {
  89.                          if (!Character.isJavaIdentifierStart(((String)node.getData()).charAt( 0 ))) {
  90.                                 System.out.print( "(" );
  91.                         }
  92.                         
  93.                         infix(node.getLeft());
  94.                         System.out.print((String)node.getData());
  95.                         infix(node.getRight());
  96.                         
  97.                          if (!Character.isJavaIdentifierStart(((String)node.getData()).charAt( 0 ))) {
  98.                                 System.out.print( ")" );
  99.                         }
  100.                 }
  101.         }
  102.         
  103.          /**
  104.          * description: print postfix exp from this tree
  105.          */
  106.          public   void  postfix(TreeNode node) {
  107.                  if (node ==  null ) {
  108.                          return ;
  109.                 }  else  {
  110.                         postfix(node.getLeft());
  111.                         postfix(node.getRight());
  112.                         System.out.print((String)node.getData());
  113.                 }
  114.         }
  115.         
  116.          /**
  117.          * description: evaluate the expression tree
  118.          * @return - the value of the expression
  119.          */
  120.          public   int  evaluate() {
  121.                 InfixToPostfixConvertor pc =  new  InfixToPostfixConvertor();
  122.                 StringBuilder sb =  new  StringBuilder();
  123.                 Random rd =  new  Random();
  124.                 String postfix =  null ;
  125.                  try  {
  126.                          // convert the original infix exp to postfix
  127.                         postfix = pc.convert( this .originalExp);
  128.                         
  129.                          // build a postfix expression string
  130.                         StringTokenizer st =  new  StringTokenizer(postfix);
  131.                          while (st.hasMoreTokens()) {
  132.                                 String next = st.nextToken();
  133.                                  if (Character.isJavaIdentifierStart(next.charAt( 0 ))) {
  134.                                          // generate the integer random for the variables of this expression
  135.                                         sb.append(rd.nextInt( 100 ));
  136.                                 }  else  {
  137.                                         sb.append(next);
  138.                                 }
  139.                                 sb.append( " " );
  140.                         }
  141.                         
  142.                         System.out.print(sb.toString() +  " = " );
  143.                         
  144.                          // call postfix evaluator
  145.                         PostfixEvaluator pe =  new  PostfixEvaluator(sb.toString());
  146.                          return  pe.eval();
  147.                         
  148.                 }  catch (Exception e) {
  149.                         e.printStackTrace();
  150.                          return   0 ;
  151.                 }
  152.         }
  153.         
  154.          /**
  155.          * description: determine whether a char is an operator
  156.          * @param op - the given char
  157.          * @return - true if the char is an operator
  158.          */
  159.          private   boolean  isOperator( char  op) {
  160.                  return  OPERATORS.indexOf(op) != - 1 ;
  161.         }
  162.          /**
  163.          * @return the root
  164.          */
  165.          public  TreeNode getRoot() {
  166.                  return  root;
  167.         }
  168.          /**
  169.          * @param root the root to set
  170.          */
  171.          public   void  setRoot(TreeNode root) {
  172.                  this .root = root;
  173.         }
  174. }
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值