本文介绍了创建二进制防爆pression树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人能解释如何构建一个二进制EX pression树。
例如我有一个字符串 2 *(1+(2 * 1));
如何转换这种成二进制EX pression树
*
| \
| \
2 +
| \
1 *
| \
2 1
解决方案
序转换为preorder或后序
后序输入是:B + C D E + **
- 在考虑第一个字符,如果它不是符号然后创建节点添加到堆栈
- 如果字符是符号然后创建节点符号的流行元素,并添加到左和符号的正确
- 在堆栈推送符号节点。
- 重复1,2和3,直到迭代器有没有更多的元素
Java实现
公共Tree.TreeNode createEx pressionTree(){
迭代器<性格> ITR = postOrder.iterator();
树树=新树();
NodeStack nodeStack =新NodeStack();
Tree.TreeNode节点;
而(itr.hasNext()){
字符c = itr.next();
如果(!ISDIGIT(c))的{
节点= tree.createNode(C);
node.right = nodeStack.pop();
node.left = nodeStack.pop();
nodeStack.push(节点);
}其他{
节点= tree.creteNode(C);
nodeStack.push(节点);
}
}
节点= nodeStack.pop();
返回节点;
}
更多信息: http://en.wikipedia.org/wiki/Binary_ex$p $ pssion_tree
Could someone explain how to build a binary expression tree.
For example I have a string 2*(1+(2*1));
How to convert this into a binary expression tree.
*
| \
| \
2 +
|\
1 *
|\
2 1
解决方案
Convert inorder to preorder or postorder
The Postorder input is: a b + c d e +**
- Consider first character if it is not symbol then create node add it to stack
- If character is symbol then create node with symbol pop elements and add to left and right of symbol
- Push symbol node in to the stack.
- Repeat 1, 2 and 3 till iterator has no more elements
Java Implementation
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;
}
More info: http://en.wikipedia.org/wiki/Binary_expression_tree
这篇关于创建二进制防爆pression树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!