Evaluation of Expression Tree
Given a simple expression tree, consisting of basic binary operators i.e., + , – ,* and / and some integers, evaluate the expression tree.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input : Root node of the below tree
Output : 100 Input : Root node of the below tree
Output : 110
As all the operators in the tree are binary hence each node will have either 0 or 2 children. As it can be inferred from the examples above, the integer values would appear at the leaf nodes, while the interior nodes represent the operators.
To evaluate the syntax tree, a recursive approach can be followed.
Algorithm : Let t be the syntax tree If t is not null then If t.info is operand then Return t.info Else A = solve(t.left) B = solve(t.right) return A operator B where operator is the info contained in t
The time complexity would be O(n), as each node is visited once. Below is a C++ program for the same:
This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.