the todo part 1 package expressiontree; 2 3 import java.util.Stack; 4 5 public c
ID: 3912629 • Letter: T
Question
the todo part
1 package expressiontree; 2 3 import java.util.Stack; 4 5 public class ExpressionTree i private Node root; private String postfix; 7 10e public class Node i 12 13 14 15e 16 17 18 19 20 21 Node left, right; String data; private Node(String s)i data-S; left-null; right-null; 23 24 25e 26 27 28 29 30 31 32 /* Initialize the tree, assign parameter, and generate the ExpressionTree * based on the postfix string. */ public ExpressionTree(String postfix) 5 root - null; this.postfix-postfix; generateTreeFromPostFixO; public Node getRoot) i return root; 34Explanation / Answer
Please find the code below:
CODE
===================
private boolean isOperator(char c) {
if (c == '+' || c == '-'
|| c == '*' || c == '/'
|| c == '^') {
return true;
}
return false;
}
private void generateTreeFromPostfix() {
Stack<Node> st = new Stack();
Node t, t1, t2;
// Traverse through every character of
// input expression
for (int i = 0; i < postfix.length(); i++) {
// If operand, simply push into stack
if (!isOperator(postfix.charAt(i))) {
t = new Node(postfix.charAt(i) + "");
st.push(t);
} else // operator
{
t = new Node(postfix.charAt(i) + "");
// Pop two top nodes
// Store top
t1 = st.pop(); // Remove top
t2 = st.pop();
// make them children
t.right = t1;
t.left = t2;
// System.out.println(t1 + "" + t2);
// Add this subexpression to stack
st.push(t);
}
}
// only element will be root of expression
// tree
root = st.peek();
st.pop();
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.