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 firstname.lastname@example.org. 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.
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.
- Stack | Set 4 (Evaluation of Postfix Expression)
- Check for balanced parentheses in an expression
- Minimum number of bracket reversals needed to make an expression balanced
- Convert a Binary Tree into its Mirror Tree
- Check if a binary tree is subtree of another binary tree | Set 1
- Convert a given tree to its Sum Tree
- Binary Tree to Binary Search Tree Conversion
- Check if a binary tree is subtree of another binary tree | Set 2
- Tree Traversals (Inorder, Preorder and Postorder)
- Write a Program to Find the Maximum Depth or Height of a Tree
- Lowest Common Ancestor in a Binary Search Tree.
- Level Order Tree Traversal
- A program to check if a binary tree is BST or not
- Check for Children Sum Property in a Binary Tree
- How to determine if a binary tree is height-balanced?
- Diameter of a Binary Tree
- Construct Tree from given Inorder and Preorder traversals
- Given a binary tree, print all root-to-leaf paths
- Find the largest BST subtree in a given Binary Tree | Set 1
- Maximum width of a binary tree