use*_*839 8 algorithm expression-trees
有人可以解释如何构建二进制表达式树.
例如,我有一个字符串2*(1+(2*1));
如何将其转换为二进制表达式树.
*
| \
| \
2 +
|\
1 *
|\
2 1
Run Code Online (Sandbox Code Playgroud)
SHA*_*SHA 11
将中缀转换为后缀或前缀
后缀输入为:ab + cde +**
Java实现
public Tree.TreeNode createExpressionTree(){
Iterator<Character>itr = postOrder.iterator();
Tree tree = new Tree();
NodeStack nodeStack = new NodeStack();
Tree.TreeNode node;
while (itr.hasNext()) {
Character c = itr.next();
if(!isDigit(c)){
node = tree.createNode(c);
node.right = nodeStack.pop();
node.left = nodeStack.pop();
nodeStack.push(node);
}else{
node = tree.creteNode(c);
nodeStack.push(node);
}
}
node = nodeStack.pop();
return node;
}
Run Code Online (Sandbox Code Playgroud)
更多信息:http://en.wikipedia.org/wiki/Binary_expression_tree
将表达式转换为前缀或后缀表示法。从那里开始应该非常简单。以下 wiki 链接中提到了算法。
http://en.wikipedia.org/wiki/Polish_notation
http://en.wikipedia.org/wiki/Reverse_Polish_notation