中序括号树遍历

问题描述

我有一个使用后缀表达式创建的二叉树,我想在其中按顺序遍历:

   private  String inorderTraverse(TreeNode t)
   {
      if(t.getLeft() == null) {
         return t.getValue().toString();
      }else{
         return inorderTraverse(t.getLeft()) + " " + t.getValue().toString() + " " + inorderTraverse(t.getRight()); 
      }
   }

其中 t 是树的根。

用于以 str 为后缀表达式创建树的方法

public void buildTree(String str)
   {
      Stack<TreeNode> stack = new Stack<TreeNode>();
      String[] expression = str.split(" ");
      for(String token : expression) {
         if(!isOperator(token)) {
            //Is a number
            TreeNode newNode = new TreeNode(token);
            stack.push(newNode);
         }else{
            //Is an operator
            TreeNode newNode = new TreeNode(token);
            newNode.setRight(stack.pop());
            newNode.setLeft(stack.pop());
            stack.push(newNode);
         }
      }
      
      root = stack.pop();   
   }

一棵树的例子:

Example of a tree

树节点类:

public class TreeNode
{
   private Object value; 
   private TreeNode left,right;
   
   public TreeNode(Object initValue) {
      value = initValue; 
      left = null; 
      right = null; 
   }
   public Object getValue() { return value;}
   
   public TreeNode getLeft() { return left;} 
   
   public TreeNode getRight() { return right;}

   /*Other methods not relevant here*/
}

但是,我必须在遍历时将括号放在适当的位置

我正在尝试做的示例:

20.0 3.0 -4 + * => 20.0 * ( 3.0 + -4 )

10 5 3 2 1 + * + * 5 + => 10 * ( 5 + 3 * ( 2 + 1 ) ) + 5

没有任何不必要的括号

我看过这个question,但是答案建议的算法在整个答案周围加上括号(以及其他不需要优先级的地方),而作者要求在周围加上括号每一个操作。快速搜索其他来源不会显示任何其他有用的信息。

问题:是否有一种遵循优先级规则的好算法来遍历顺序?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)