Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

The program below is used to construct an expression tree. You need to fill the body for the inorder function (which does inorder traversal) so

The program below is used to construct an expression tree. You need to fill the body for the inorder function (which does inorder traversal) so that the output is:

infix expression is

5 + 6 - 8 * 3 * 2

Attach your code and screenshots of the output here.

// Java program to construct an expression tree

importjava.util.Stack;

// Java program for expression tree

class Node {

char value;

Node left, right;

Node(char item) {

value = item;

left = right = null;

}

}

class ExpressionTree {

// A utility function to check if 'c'

// is an operator

booleanisOperator(char c) {

if (c == '+' || c == '-'

|| c == '*' || c == '/'

|| c == '^') {

return true;

}

return false;

}

// Utility function to do inorder traversal

voidinorder(Node t) {

// Implement the inorder traversal here

}

// Returns root of constructed tree for given

// postfix expression

Node constructTree(char postfix[]) {

Stackst = new Stack();

Node t, t1, t2;

// Traverse through every character of

// input expression

for (inti = 0; i

// If operand, simply push into stack

if (!isOperator(postfix[i])) {

t = new Node(postfix[i]);

st.push(t);

} else // operator

{

t = new Node(postfix[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

t = st.peek();

st.pop();

return t;

}

public static void main(String args[]) {

ExpressionTree et = new ExpressionTree();

String postfix = "56+83*2*-";

char[] charArray = postfix.toCharArray();

Node root = et.constructTree(charArray);

System.out.println("infix expression is");

et.inorder(root);

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

XML Data Management Native XML And XML Enabled Database Systems

Authors: Akmal Chaudhri, Awais Rashid, Roberto Zicari, John Fuller

1st Edition

0201844524, 978-0201844528

More Books

Students also viewed these Databases questions