Creating a binary tree from a math expression

I have an expression like ((2+8)*8)-(5*(5+2)) Or + 2 + 1 1 . And I want to make a binary tree in this.

  + / \ 2 + / \ 1 1 

How can I create this binary tree?

+4
source share
2 answers

I had a similar project, and here is how I did it:

  • Mark the line. See what each character is. For example, a list may contain:

      '(' Open parantheses
     '11' Number
     '+' Operator etc 
  • Convert the expression to postfix (or prefix, if you want) notation. One algorithm that can do this is called the Shunting Yard algorithm. The advantage of postfix notation is that you can much more easily evaluate an expression using a stack-based method (or a binary tree, if you want).

  • Rate the postfix expression. You can do this in two ways: a binary tree and a stack.

Stack Rating:

Your expression expression converted to postfix notation will look like this:

 2 8 + 8 * 5 5 2 + * - 

The evaluation is performed as follows: when you encounter a number, click it on the stack. When you come across an operator, put 2 items from the stack, do the calculations and push the result on the stack. In the end, you must stay with the final result.

In the above example, this is what we will do:

 Push 2 [Stack content: 2] Push 8 [2 8] Pop 2 and 8 [] Push 2+8 [10] Push 8 [10 8] Pop 10 and 8 [] Push 10*8 [80] Push 5 [80 5] Push 5 [80 5 5] Push 2 [80 5 5 2] Pop 2 and 5 [80 5] Push 2 + 5 [80 5 7] Pop 7 and 5 [80] Push 7 * 5 [80 35] Pop 80 and 35 [] Push 80 - 35 [45] Final result is 45. 

Binary tree

Here's how I do it: just like the stack-based one, use the node stack. When you come across an operator, you pop 2 elements from the stack, but instead of evaluating you create a node with the operator and make it a parent of two pop-up elements. Then you push node back onto the stack.

The disadvantage of this approach is that you have an extra step: creating a tree.

Final notes

This is the method I would use. There may be more effective methods than this, but that is exactly how I would do it.

+7
source
+2
source

Source: https://habr.com/ru/post/1433705/


All Articles