Given a simple expression tree, consisting of basic binary operators i.e., + , – ,* and / and some integers, evaluate the expression tree.
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 contribute.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.
- Building Expression tree from Prefix Expression
- Expression Tree
- Convert Ternary Expression to a Binary Tree
- Check for balanced parentheses in an expression
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Convert a given Binary tree to a tree that holds Logical AND property
- Sub-tree with minimum color difference in a 2-coloured tree
- Convert a Binary Tree into its Mirror Tree
- Create a mirror tree from the given binary tree