开发者

Create recursive binary tree?

I have two stacks, one with operands, the other with operators. My problem is turning these two stacks into a binary tree.

For example, the expression (2+3)*(4-3) will be transl开发者_如何学Goated into postfix ( such that 24+43-*) and then put into two stacks 3442 and *-+ will be the stacks (with the tops being 3 and * respectively).

Now with these stacks, i need to form a binary tree like

   *
 +    -
2 3  4 3

Is there a way to do this recursively?

Right now, I have an algorithm like so:

  • Create the root of the tree, assign the value of the root to the first operator in the operator-stack. Set the right and left pointers to null.

  • Create the right node, assign the value of the next operator if it exists, if not assign it an operand. Then do the same for the left node.

My problem is making this recursive, or getting it to handle the many different cases.

Thanks for your help.


assuming you have only binary operators

treeNode createNode(operators, operands) {
  // take first operator and create a new treeNode with it. pop it from the operators stack 

  // if it is the last operator in the list then there should be only two operands left in the operands and you can assign them to the left and right child of the treeNode. return this treeNode.

  // if it is not the last operator then split the operands in two stacks equally
  // leftOperands and rightOperands
  // left child becomes createNode(operators, leftoperands)
  // right child becomes createNode(operators, rightoperands)
  // return this treeNode

}


Recursive algorithm:

  • find the highest priority operator
  • split the expression around this operator
  • recursively apply on both parts


if your expression is always symmetrical (the same number of operands and operators on each side of an operator), then the method you describe works fine, with a little modification:

  1. create a node, assign the value of the top operator in the operator stack.
  2. if there are no operator left on the operator stack, pop the 2 operands from the operands stack and assign them to the left and right branch, then exit
  3. if there are any operator on the stack, go to the left brach of your node and call your algorithm, then go to the right branch and call your algorithm.

(Jan explained it so much clearer in his answer...)


In general there isn't a way of doing this. Does "1 2 3 4" "* + /" mean "1 2 3 4 * + /" (that is, "1 / (2 + 3 * 4)") or "1 2 * 3 + 4 /" , (that is "(1 * 2 + 3) / 4").

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜