Question

Write a simple java program that takes input from the user as a fully parenthesized expression...

Write a simple java program that takes input from the user as a fully parenthesized expression and converts it to a binary tree. Ex: (1+2 * (6-4)) or (A+B / (D-C))

When the tree is built, it should print the tree in some way.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.util.Stack; class Node { char value; Node left, right; Node(char item) { value = item; left = right = null; } } class ExpressionTree { boolean isOperator(char c) { if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^') { return true; } return false; } void inorder(Node t) { if (t != null) { inorder(t.left); System.out.print(t.value + " "); inorder(t.right); } } Node constructTree(char postfix[]) { Stack<Node> st = new Stack(); Node t, t1, t2; for (int i = 0; i < postfix.length; i++) { if (!isOperator(postfix[i])) { t = new Node(postfix[i]); st.push(t); } else { t = new Node(postfix[i]); t1 = st.pop(); t2 = st.pop(); t.right = t1; t.left = t2; st.push(t); } } t = st.peek(); st.pop(); return t; } } public class Main { public static void main(String[] args) { ExpressionTree et = new ExpressionTree(); String postfix = "(1+2*(6-4))"; char[] charArray = postfix.toCharArray(); Node root = et.constructTree(charArray); System.out.println("infix expression is"); et.inorder(root); } }
Add a comment
Know the answer?
Add Answer to:
Write a simple java program that takes input from the user as a fully parenthesized expression...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT