如何解决中序括号树遍历
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();
}
一棵树的例子:
树节点类:
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 举报,一经查实,本站将立刻删除。