In Java please, and please print output to make sure it is correct Complete the
ID: 3675807 • Letter: I
Question
In Java please, and please print output to make sure it is correct
Complete the following method buildExprTree(String postfix) that takes a postfix expression as input and builds the corresponding expression tree. For instance if the given postfix expression is "3 5 + 4/", the expression tree is as in below image. Assume all arithmetic operations are binary. You may further assume that the input postfix expression will always be a valid postfix expression, in other words, you do not have to consider error cases. (You may assume that you have access to a Stack class.) void buildExprTree(String postfix) { StringTokenizer tokens = new StringTokenizer(postfix); while (tokens.hasMoreTokens()) { String nextToken = tokens.nextToken();Explanation / Answer
// I have wrote thr code for the function, but since you have not given the sample input/output, I con't know how the flow should be
import java.util.Stack;
import java.util.StringTokenizer;
public class Test{
class Node{
String data;
Node left, right;
public Node(String d, Node l, Node r){
data = d;
left = l;
right = r;
}
}
void buildExprTree(String postfix){
Stack<Node> s = new Stack<Node>();
StringTokenizer tokens = new StringTokenizer(postfix);
while(tokens.hasMoreTokens()){
String nextToken = tokens.nextToken();
if(nextToken.equals("+") || nextToken.equals("-") || nextToken.equals("*") || nextToken.equals("/")){
Node op1 = s.pop();
Node op2 = s.pop();
Node temp = new Node(nextToken, op1, op2);
s.push(temp);
}
else{
s.push(new Node(nextToken, null, null));
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.