我复制了算法,用这里的堆栈来做: How to put postfix expressions in a binary tree?
问题是我最终得到了一个节点,但我需要一个二叉树。
String currentPartOfEquation;
Stack<Node<String>> inputProcessor = new Stack(postFixExpression.size()); //create a stack of the size of how many parts there are to the expression. technically, a length of a string.
Iterator<String> lookThroughInput = postFixExpression.iterator();
//iterate through the input!
BinaryTree<String> output = new BinaryTree<String>();
while(lookThroughInput.hasNext()) //Is there something left?
{
currentPartOfEquation = lookThroughInput.next(); //we read next input! We read one symbol of a postfix expression.
if(currentPartOfEquation.equals("*") ||
currentPartOfEquation.equals("/") || currentPartOfEquation.equals("-")
|| currentPartOfEquation.equals("+")) //Do we have a math operator as the symbol read in the expression?
{
//the first extracted off stack will end up being a right child for the current operator....
//we're popping based on an algorithm
//of making leaf nodes for #s following with
//giving 'em families with the operator input found here as a parent.
Node<String> right = inputProcessor.pop();
//operator's children!!!!
Node<String> left = inputProcessor.pop();
// operator node with its family relations. no parent yet, so null for that field
// we are creating a tree every time using the class definition.
Node<String> parent = createNode(currentPartOfEquation, temp, left, right);
temp = parent;
//for a parental connection for each next op to each previous op.
// push this family node into our stack using the class definition.
inputProcessor.push(parent);
}
else //we see a number in our input!!!
{
//no parents or children, just the NUMBER stored in a node!!!!!!! it's our LEAF NODE!!!!
Node<String> leaf = createNode(currentPartOfEquation, null, null, null);
// push this leaf node holding a # into our stack!!!!!
inputProcessor.push(leaf);
}
}
return inputProcessor.top();
// at the end there should be be one element in the stack holding the entire family in correct order!!!!! this tree should be created by the very end.
有关二进制树如何与节点相关的一些信息:
节点实现位置以及它们的连接方式。 node是一个内部类,包含父,左,右(所有节点)和元素(对象)作为实例变量。
Node类中的构造函数指定元素,父元素,左元素,右元素。二进制树包含一个名为root的实例变量Node,它是树的顶层元素 - 根 - 而createNode也是它的功能。
createNode确实返回新节点,并将元素,父,左,右分别对应于Node的构造函数。
通过二叉树的方法(它们都返回位置并从参数中获取位置,但是使用节点),二叉树连接节点(像右边添加,左边添加等)
二进制树中的验证方法经常使用一个位置并将其作为节点返回。