I was wondering how inserting an equation such as 5 * 4 + 2 / 3
into a binary tree would work. I have tried doing this on my own however I can only make the tree grow to one side.
Asked
Active
Viewed 219 times
0

User9123
- 675
- 1
- 8
- 20
-
What do you want to achieve ? – alamit Nov 04 '18 at 02:57
-
i just want to create an expression tree – User9123 Nov 04 '18 at 02:58
-
1It is hard to see what you are doing wrong if you don't show us your code. – HAL9000 Nov 04 '18 at 02:59
-
i am not looking for code, just a logical explanation on how to create the tree – User9123 Nov 04 '18 at 03:01
-
A good place to start is [Shunting-yard algorithm](https://en.wikipedia.org/wiki/Shunting-yard_algorithm). See also https://stackoverflow.com/questions/33297807/polish-prefix-notation-logical-expression-to-expression-tree-and-back, which has a lot of good information links. – Jim Mischel Nov 04 '18 at 16:39
1 Answers
1
I am not an expert in the field, but I wrote basic expression parsers in the past.
You will need to
tokenize
your expression. Transform it from a string of characters to alist
of understandable chunks.You may want to create two structures, one for operators and one for operands. Hint, operators have a priority associated with them.
You can apply an algorithm to transform your operators/operands to an
abstract syntax tree
(AST) it's basically just a set of rules, generally used with a queue and a stack.

Swann
- 2,413
- 2
- 20
- 28