2015-12-01 1 views
0

Так что моя цель превратить какое-то выражение в постфиксное выражение (check), а затем преобразовать это выражение в двоичное дерево. Вот мой основной классКод help, не может получить двоичное дерево

public class ConvertIntoTree 
{ 
    public static void main(String[] args) 
    { 
     // Create a new InfixToPostfix expression from input 
     InfixtoPostfix mystack = new InfixtoPostfix(15); 
     System.out.println("Type in an expression like (1+2)*(3+4)/(12-5) //No spaces "); 
     Scanner scan = new Scanner(System.in); 
     String str = scan.next(); 
     System.out.println("The Expression you have typed in infix form :\n"+str); 
     System.out.println("The Expression in Postfix is :\n"+mystack.InToPost(str)); 

     ExpressionTree expressionTree = new ExpressionTree(str); 
     expressionTree.createExpressionTree(); 
     //expressionTree.prefix(); 
     System.out.println("The Expression I want"); 
     expressionTree.infix();   
    } 

} 

и вот мое выражение дерево класс

class ExpressionTree { 

    private final String postfix; 
    private TreeNode root; 

    /** 
    * Takes in a valid postfix expression and later its used to construct the expression tree. 
    * The posfix expression, if invalid, leads to invalid results 
    * 
    * @param postfix the postfix expression. 
    */ 
    public ExpressionTree(String postfix) { 
     if (postfix == null) { throw new NullPointerException("The posfix should not be null"); } 
     if (postfix.length() == 0) { throw new IllegalArgumentException("The postfix should not be empty"); } 
     this.postfix = postfix; 
    } 

    private static class TreeNode { 
     TreeNode left; 
     char ch; 
     TreeNode right; 

     TreeNode(TreeNode left, char ch, TreeNode right) { 
      this.left = left; 
      this.ch = ch; 
      this.right = right; 
     } 
    } 


    private boolean isOperator(char c) { 
     return c == '+' || c == '-' || c == '*' || c == '/'; 
    } 


    /** 
    * Constructs an expression tree, using the postfix expression 
    */ 
    public void createExpressionTree() { 
     final Stack<TreeNode> nodes = new Stack<TreeNode>(); 
     for (int i = 0; i < postfix.length(); i++) { 
      char ch = postfix.charAt(i); 
      if (isOperator(ch)) { 
       TreeNode rightNode = nodes.pop(); 
       TreeNode leftNode = nodes.pop(); 
       nodes.push(new TreeNode(leftNode, ch, rightNode)); 
      } else { 
       nodes.add(new TreeNode(null, ch, null)); 
      } 
     } 
     root = nodes.pop(); 
    } 


    /** 
    * Returns the prefix notation 
    * 
    * @return the prefix notation 
    */ 
    public String prefix() { 
     if (root == null) { 
      throw new NoSuchElementException("The root is empty, the tree has not yet been constructed."); 
     } 

     final StringBuilder prefix = new StringBuilder(); 
     preOrder(root, prefix); 
     return prefix.toString(); 
    } 

    private void preOrder(TreeNode node, StringBuilder prefix) { 
     if (node != null) { 
      prefix.append(node.ch); 
      preOrder(node.left, prefix); 
      preOrder(node.right, prefix); 
     } 
    } 

    /** 
    * Returns the infix expression 
    * 
    * @return the string of infix. 
    */ 
    public String infix() { 
     if (root == null) { 
      throw new NoSuchElementException("The root is empty, the tree has not yet been constructed."); 
     } 
     final StringBuilder infix = new StringBuilder(); 
     inOrder(root, infix); 
     return infix.toString(); 
    } 

    private void inOrder(TreeNode node, StringBuilder infix) { 
     if (node != null) { 
      inOrder(node.left, infix); 
      infix.append(node.ch); 
      inOrder(node.right, infix); 
     } 

    } 

} 

После того как я не запустить expressionTree.infix();, ничего. Очевидно, я делаю что-то неправильно. Любые идеи или помощь, спасибо.

+1

Я бы предложил попробовать отладчик - например, от Eclipse. Это должно дать вам представление о том, что происходит на самом деле, когда ваш код работает, и из этого вы сможете определить, что пошло не так. –

+1

Как насчет печати возвращаемого значения infix? – JFPicard

+0

Что такое InfixtoPostfix? –

ответ

0

После небольшого лужения, основной вопрос с помощью expressionTree2.infix() вместо System.out.println(expressionTree2.infix());