Create recursive binary tree?

社会主义新天地 提交于 2019-12-11 02:14:59

问题


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 translated 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.


回答1:


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

}



回答2:


Recursive algorithm:

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



回答3:


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...)




回答4:


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").



来源:https://stackoverflow.com/questions/4155975/create-recursive-binary-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!