Expression tree is a binary tree in which each internal node corresponds to operator and each leaf node corresponds to operand so for example expression tree for 3 + ((5+9)*2) would be:
Inorder traversal of expression tree produces infix version of given postfix expression (same with preorder traversal it gives prefix expression)
Evaluating the expression represented by expression tree:
Let t be the expression tree If t is not null then If t.value is operand then Return t.value A = solve(t.left) B = solve(t.right) // calculate applies operator 't.value' // on A and B, and returns value Return calculate(A, B, t.value)
Construction of Expression Tree:
Now For constructing expression tree we use a stack. We loop through input expression and do following for every character.
1) If character is operand push that into stack
2) If character is operator pop two values from stack make them its child and push current node again.
At the end only element of stack will be root of expression tree.
Below is the implementation :
infix expression is a + b - e * f * g
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Building Expression tree from Prefix Expression
- Evaluation of Expression Tree
- Convert Ternary Expression to a Binary Tree
- Program to convert Infix notation to Expression Tree
- Convert ternary expression to Binary Tree using Stack
- 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
- Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- Check if max sum level of Binary tree divides tree into two equal sum halves
- 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 OR property
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Convert a given Binary tree to a tree that holds Logical AND property
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Cartesian tree from inorder traversal | Segment Tree
- Sub-tree with minimum color difference in a 2-coloured tree
- Minimum difference between any two weighted nodes in Sum Tree of the given Tree
Improved By : andrew1234