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.
- Building Expression tree from Prefix Expression
- Evaluation of Expression Tree
- Convert Ternary Expression to a Binary Tree
- 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
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Convert a given Binary tree to a tree that holds Logical AND property
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Sub-tree with minimum color difference in a 2-coloured tree
- Convert a Binary Tree into its Mirror Tree
- Minimum swap required to convert binary tree to binary search tree
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)