前缀表达式的树构造
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
我们举个例子:+ 2 + 1 1
应用 (0)。
+
应用 (1)。
+
/
2
应用 (2)。
+
/ \
2 +
应用 (1)。
+
/ \
2 +
/
1
最后,应用(2)。
+
/ \
2 +
/ \
1 1
该算法已经针对- * / 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 = ?
评估树有点有趣,因为您必须从树的右下角开始。执行反向post-order 遍历。首先访问正确的孩子。
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
鉴于从前缀表达式构造树的简单性,我建议使用标准 stack algorithm 将中缀转换为前缀。在实践中,您会使用堆栈算法来计算中缀表达式。