The expression tree is a binary tree in which each internal node corresponds to the operator and each leaf node corresponds to the 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 an 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 an expression tree we use a stack. We loop through input expression and do the following for every character.
- If a character is an operand push that into the stack
- If a character is an operator pop two values from the stack make them its child and push the current node again.
In the end, the only element of the stack will be the root of an expression tree.
Below is the implementation of the above approach:
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.
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.
- Building Expression tree from Prefix Expression
- Evaluation of Expression Tree
- Convert Ternary Expression to a Binary Tree
- Convert ternary expression to Binary Tree using Stack
- Program to convert Infix notation to Expression Tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Convert a Generic Tree(N-array Tree) to Binary Tree
- Convert a Binary Tree into its Mirror Tree
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- 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 given Binary Tree is height balanced like a Red-Black Tree
- Check if a binary tree is subtree of another binary tree | Set 2
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Check whether a binary tree is a full binary tree or not
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- Minimum swap required to convert binary tree to binary search tree