I have a expression like ((2+8)*8)-(5*(5+2)) Or + 2 + 1 1 . And I want to make a binary tree in that .
+
/ \
2 +
/ \
1 1
How can I Make this Binary tree?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I had a similar project, and this is how I did it:
Tokenize the string. See what each symbol is. For example, the list may contain:
'(' Open parantheses '11' Number '+' Operator etcConvert the expression to postfix (or prefix if you want) notation. One algorithm that can do that is called the Shunting Yard algorithm. The advantage of postfix notation is that you can evaluate the expression much easier, using a stack-based method (or binary tree if you want).
Evaluate the postfix expression. You can do it in two ways, a binary tree and stack.
Stack evaluation:
Your example expression converted in postfix notation will look like this:
Evaluating works like this: When you encounter a number, push it on the stack. When you encounter an operator, pop 2 items from the stack, make the calculation, and push the result on the stack. In the end, you should be left with the final result.
For the example above, this is what we will do:
Binary tree
This is how I would do it: just like the stack based approach, use a stack of nodes. When you encounter an operator, you pop 2 items from the stack, but instead of evaluating, you create a node with the operator, and make it the parent of the 2 popped items. Then you push the node back on the stack.
The disadvantage of this approach is that you have an additional step: creating the tree.
Final notes
This is the method I would use. Maybe there are more efficient methods than this, but this is how I would do it.