Amazon Interview Question
Software Engineer / DevelopersThis code has bug
ab+cd* gets converted to two subtrees a + b and c * d but these two subtrees are not connected and program would return only the subtree at the top.
I think the question is not about data structure to be used for expression tree but a design for it.
I can think of a following class structure:
abstract class Node{
}
class OperatorNode extends Node{
Node leftNode;
Node rightNode;
int operator;//constants for +,-,*,/
}
class OperandNode extends Node{
int number;
}
}
I think what the question means if - if you are given an infix/postfix expression, make an expression tree out of it.
Eg. Convert a postfix expression into an expression tree
Algorithm:
1. Intialize a stack to store binary tree nodes.
2. Read the array from left to right.
3. If you come across an operand, make a node out of it and push into the stack.
If its an operator, pop two nodes from the stack and first popped node would be the operator node's right child and the second popped node would be the operator node's left child. Push the operator node into the stack
4.The last popped node would be the head of the tree.
- Dragon March 04, 2012