Ani*_*ila 2 java tree parsing binary-tree
我必须用Java创建一个算术求值器.为此,我必须在二叉树中解析一个algebric表达式,然后计算并返回结果.因此,对于第一步,我如何解析二叉树中的表达式?我知道这个理论,但我的问题是如何用Java做到这一点.我阅读了以下帖子 创建递归二叉树
但我错过了基本的技巧或方法.我知道如何创建一个节点(我有一个类,其方法有returnNodeValue,isLeaf,isDoubleNode,isSingleNode等),但我想我需要一个方法在二叉树中插入一个节点来实现我想要的东西.有任何想法吗?
前缀表达式的树构造
def insert
Insert each token in the expression from left to right:
(0) If the tree is empty, the first token in the expression (must
be an operator) becomes the root
(1) Else if the last inserted token is an
operator, then insert the token as the left child of the last inserted
node.
(2) Else if the last inserted token is an operand, backtrack up the
tree starting from the last inserted node and find the first node with a NULL
right child, insert the token there. **Note**: don't insert into the last inserted
node.
end def
Run Code Online (Sandbox Code Playgroud)
我们举个例子: + 2 + 1 1
申请(0).
+
Run Code Online (Sandbox Code Playgroud)
申请(1).
+
/
2
Run Code Online (Sandbox Code Playgroud)
申请(2).
+
/ \
2 +
Run Code Online (Sandbox Code Playgroud)
申请(1).
+
/ \
2 +
/
1
Run Code Online (Sandbox Code Playgroud)
最后,申请(2).
+
/ \
2 +
/ \
1 1
Run Code Online (Sandbox Code Playgroud)
该算法已经过测试 - * / 15 - 7 + 1 1 3 + 2 + 1 1
所以Tree.insert实施就是这三个规则.
insert(rootNode, token)
//create new node with token
if (isLastTokenOperator)//case 1
//insert into last inserted's left child
else { //case 2
//backtrack: get node with NULL right child
//insert
}
//maintain state
lastInsertedNode = ?, isLastTokenOperator = ?
Run Code Online (Sandbox Code Playgroud)
评估树有点好笑,因为你必须从树的右下角开始.执行反向的订单后遍历.先访问合适的孩子.
evalPostorder(node)
if (node == null) then return 0
int rightVal = evalPostorder(node.right)
int leftVal = evalPostorder(node.left)
if(isOperator(node.value))
return rightVal <operator> leftVal
else
return node.value
Run Code Online (Sandbox Code Playgroud)
鉴于从前缀表达式构造树的简单性,我建议使用标准堆栈算法从中缀转换为前缀.在实践中,您将使用堆栈算法来评估中缀表达式.
我认为您可能对应该做的事情有些困惑:
...但是我想我需要一种在二叉树中插入节点的方法...
您正在谈论的二叉树实际上是一个解析树,并且它并不是严格意义上的二叉树(因为并非所有树节点都是二叉树)。(除了“二叉树”之外,还有二叉搜索树的含义,这根本不是您所需要的。)
您已经解析出一个表达式,解析树的构造非常简单。例如:
Tree parseExpression() {
// ....
// binary expression case:
Tree left = parseExpression();
// parse operator
Tree right = parseExpression();
// lookahead to next operator
if (...) {
} else {
return new BinaryNode(operator, left, right);
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
注意:这不是有效的代码...这是帮助您完成家庭作业的提示。