SlideShare a Scribd company logo
1 of 14
Download to read offline
Please read the comment ins code
ExpressionTree.java
----------------------------------
/**
* This is the class for Expression Tree.
* Used to create Expression Tree and Evaluate it
*/
/**
* Following logic is used to construct a Tree
* Here we use stack for Preparing Tree
* Loop through given Expression String
* If Character is Operand , Create node and push to stack
* If Character is Operator then
* 1)Create Node for Operator
* 2)Pop 2 nodes from Stack and Made
* OpretorNode--> left == first node pop
* OpretorNode--> right == second node pop
* At the end of creation of Expression Tree, Stack have only one node , which is root of
Expression tree
*/
/** Class ExpressionTree **/
class ExpressionTree
{
/** class TreeNode
* Stored Character ==> Digit(0..9) or a Operator +,-,*,/
* Left Node and Right Node
*
* **/
class TreeNode
{
char data;
TreeNode left, right;
/** constructor **/
public TreeNode(char data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
/** class StackNode **/
class StackNode
{
TreeNode treeNode;
StackNode next;
/** constructor **/
public StackNode(TreeNode treeNode)
{
this.treeNode = treeNode;
next = null;
}
}
private static StackNode top;
/** constructor
* Constructor takes input string like "+-+7*935*82*625"
* Input should be in Prefix notation
* **/
public ExpressionTree(String expression)
{
top = null;
//Call Method for prepare expression tree
buildTree(expression);
}
/** function to clear tree **/
public void clear()
{
top = null;
}
/** function to push a node **/
private void push(TreeNode ptr)
{
if (top == null)
top = new StackNode(ptr);
else
{
StackNode nptr = new StackNode(ptr);
nptr.next = top;
top = nptr;
}
}
/** function to pop a node
* When it find operator pop 2 elements from Stack
*
* **/
private TreeNode pop()
{
if (top == null)
throw new RuntimeException("Underflow");
else
{
TreeNode ptr = top.treeNode;
top = top.next;
return ptr;
}
}
/** function to get top node **/
private TreeNode peek()
{
return top.treeNode;
}
/** function to insert character **/
private void insert(char val)
{
try
{
//If Operand , Create node and push to Stack
if (isDigit(val))
{
TreeNode nptr = new TreeNode(val);
push(nptr);
}
//If Operator , Create node and popup 2 elements and make them its right and left
else if (isOperator(val))
{
TreeNode nptr = new TreeNode(val);
nptr.left = pop();
nptr.right = pop();
push(nptr);
}
}
catch (Exception e)
{
System.out.println("Invalid Expression");
}
}
/** function to check if digit **/
private boolean isDigit(char ch)
{
return ch >= '0' && ch <= '9';
}
/** function to check if operator **/
private boolean isOperator(char ch)
{
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
/** function to convert character to digit **/
private int toDigit(char ch)
{
return ch - '0';
}
/** function to build tree from input */
public void buildTree(String eqn)
{
for (int i = eqn.length() - 1; i >= 0; i--)
insert(eqn.charAt(i));
}
/** function to evaluate tree */
public double evaluate()
{
return evaluate(peek());
}
/** function to evaluate tree
*
* */
public double evaluate(TreeNode ptr)
{
if (ptr.left == null && ptr.right == null)
return toDigit(ptr.data);
else
{
double result = 0.0;
double left = evaluate(ptr.left);
double right = evaluate(ptr.right);
char operator = ptr.data;
switch (operator)
{
case '+' : result = left + right; break;
case '-' : result = left - right; break;
case '*' : result = left * right; break;
case '/' : result = left / right; break;
default : result = left + right; break;
}
return result;
}
}
/** function to get postfix expression */
public void postfix()
{
postOrder(peek());
}
/** post order traversal */
private void postOrder(TreeNode ptr)
{
if (ptr != null)
{
postOrder(ptr.left);
postOrder(ptr.right);
System.out.print(ptr.data);
}
}
/** function to get infix expression */
public void infix()
{
inOrder(peek());
}
/** in order traversal */
private void inOrder(TreeNode ptr)
{
if (ptr != null)
{
inOrder(ptr.left);
System.out.print(ptr.data);
inOrder(ptr.right);
}
}
/** function to get prefix expression */
public void prefix()
{
preOrder(peek());
}
/** pre order traversal */
private void preOrder(TreeNode ptr)
{
if (ptr != null)
{
System.out.print(ptr.data);
preOrder(ptr.left);
preOrder(ptr.right);
}
}
}
ExpressionTreeTest.java , class to test
------------------------------------------------------------
import java.util.Scanner;
/** class ExpressionTreeTest **/
public class ExpressionTreeTest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Expression Tree Test");
System.out.println(" Enter equation in prefix form");
/** make object of ExpressionTree **/
ExpressionTree et = new ExpressionTree(scan.next());
System.out.print(" Prefix : ");
et.prefix();
System.out.print("  Infix : ");
et.infix();
System.out.print("  Postfix : ");
et.postfix();
System.out.println("  Evaluated Result : "+ et.evaluate());
}
}
Solution
Please read the comment ins code
ExpressionTree.java
----------------------------------
/**
* This is the class for Expression Tree.
* Used to create Expression Tree and Evaluate it
*/
/**
* Following logic is used to construct a Tree
* Here we use stack for Preparing Tree
* Loop through given Expression String
* If Character is Operand , Create node and push to stack
* If Character is Operator then
* 1)Create Node for Operator
* 2)Pop 2 nodes from Stack and Made
* OpretorNode--> left == first node pop
* OpretorNode--> right == second node pop
* At the end of creation of Expression Tree, Stack have only one node , which is root of
Expression tree
*/
/** Class ExpressionTree **/
class ExpressionTree
{
/** class TreeNode
* Stored Character ==> Digit(0..9) or a Operator +,-,*,/
* Left Node and Right Node
*
* **/
class TreeNode
{
char data;
TreeNode left, right;
/** constructor **/
public TreeNode(char data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
/** class StackNode **/
class StackNode
{
TreeNode treeNode;
StackNode next;
/** constructor **/
public StackNode(TreeNode treeNode)
{
this.treeNode = treeNode;
next = null;
}
}
private static StackNode top;
/** constructor
* Constructor takes input string like "+-+7*935*82*625"
* Input should be in Prefix notation
* **/
public ExpressionTree(String expression)
{
top = null;
//Call Method for prepare expression tree
buildTree(expression);
}
/** function to clear tree **/
public void clear()
{
top = null;
}
/** function to push a node **/
private void push(TreeNode ptr)
{
if (top == null)
top = new StackNode(ptr);
else
{
StackNode nptr = new StackNode(ptr);
nptr.next = top;
top = nptr;
}
}
/** function to pop a node
* When it find operator pop 2 elements from Stack
*
* **/
private TreeNode pop()
{
if (top == null)
throw new RuntimeException("Underflow");
else
{
TreeNode ptr = top.treeNode;
top = top.next;
return ptr;
}
}
/** function to get top node **/
private TreeNode peek()
{
return top.treeNode;
}
/** function to insert character **/
private void insert(char val)
{
try
{
//If Operand , Create node and push to Stack
if (isDigit(val))
{
TreeNode nptr = new TreeNode(val);
push(nptr);
}
//If Operator , Create node and popup 2 elements and make them its right and left
else if (isOperator(val))
{
TreeNode nptr = new TreeNode(val);
nptr.left = pop();
nptr.right = pop();
push(nptr);
}
}
catch (Exception e)
{
System.out.println("Invalid Expression");
}
}
/** function to check if digit **/
private boolean isDigit(char ch)
{
return ch >= '0' && ch <= '9';
}
/** function to check if operator **/
private boolean isOperator(char ch)
{
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
/** function to convert character to digit **/
private int toDigit(char ch)
{
return ch - '0';
}
/** function to build tree from input */
public void buildTree(String eqn)
{
for (int i = eqn.length() - 1; i >= 0; i--)
insert(eqn.charAt(i));
}
/** function to evaluate tree */
public double evaluate()
{
return evaluate(peek());
}
/** function to evaluate tree
*
* */
public double evaluate(TreeNode ptr)
{
if (ptr.left == null && ptr.right == null)
return toDigit(ptr.data);
else
{
double result = 0.0;
double left = evaluate(ptr.left);
double right = evaluate(ptr.right);
char operator = ptr.data;
switch (operator)
{
case '+' : result = left + right; break;
case '-' : result = left - right; break;
case '*' : result = left * right; break;
case '/' : result = left / right; break;
default : result = left + right; break;
}
return result;
}
}
/** function to get postfix expression */
public void postfix()
{
postOrder(peek());
}
/** post order traversal */
private void postOrder(TreeNode ptr)
{
if (ptr != null)
{
postOrder(ptr.left);
postOrder(ptr.right);
System.out.print(ptr.data);
}
}
/** function to get infix expression */
public void infix()
{
inOrder(peek());
}
/** in order traversal */
private void inOrder(TreeNode ptr)
{
if (ptr != null)
{
inOrder(ptr.left);
System.out.print(ptr.data);
inOrder(ptr.right);
}
}
/** function to get prefix expression */
public void prefix()
{
preOrder(peek());
}
/** pre order traversal */
private void preOrder(TreeNode ptr)
{
if (ptr != null)
{
System.out.print(ptr.data);
preOrder(ptr.left);
preOrder(ptr.right);
}
}
}
ExpressionTreeTest.java , class to test
------------------------------------------------------------
import java.util.Scanner;
/** class ExpressionTreeTest **/
public class ExpressionTreeTest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Expression Tree Test");
System.out.println(" Enter equation in prefix form");
/** make object of ExpressionTree **/
ExpressionTree et = new ExpressionTree(scan.next());
System.out.print(" Prefix : ");
et.prefix();
System.out.print("  Infix : ");
et.infix();
System.out.print("  Postfix : ");
et.postfix();
System.out.println("  Evaluated Result : "+ et.evaluate());
}
}

More Related Content

Similar to Please read the comment ins codeExpressionTree.java-------------.pdf

Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfarjuncorner565
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxNew folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxcurwenmichaela
 
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfanukoolelectronics
 
#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdfKUNALHARCHANDANI1
 
Binary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureBinary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureZarghamullahShah
 
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdfPart 1)#include stdio.h #include stdlib.h #include pthrea.pdf
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdfmohammadirfan136964
 
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfUsing NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfsiennatimbok52331
 
solution in c++program Program to implement a queue using two .pdf
solution in c++program Program to implement a queue using two .pdfsolution in c++program Program to implement a queue using two .pdf
solution in c++program Program to implement a queue using two .pdfbrijmote
 
Once you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docxOnce you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docxfarrahkur54
 
Write a program that displays an AVL tree along with its balance fac.docx
 Write a program that displays an AVL tree  along with its balance fac.docx Write a program that displays an AVL tree  along with its balance fac.docx
Write a program that displays an AVL tree along with its balance fac.docxajoy21
 
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdfA)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdfanton291
 
Write a function in C++ to generate an N-node random binary search t.pdf
Write a function in C++ to generate an N-node random binary search t.pdfWrite a function in C++ to generate an N-node random binary search t.pdf
Write a function in C++ to generate an N-node random binary search t.pdfinfo824691
 
Given the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdfGiven the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdfillyasraja7
 

Similar to Please read the comment ins codeExpressionTree.java-------------.pdf (20)

Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxNew folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
 
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
 
#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf
 
Binary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureBinary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structure
 
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdfPart 1)#include stdio.h #include stdlib.h #include pthrea.pdf
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf
 
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfUsing NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
 
solution in c++program Program to implement a queue using two .pdf
solution in c++program Program to implement a queue using two .pdfsolution in c++program Program to implement a queue using two .pdf
solution in c++program Program to implement a queue using two .pdf
 
Once you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docxOnce you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docx
 
Write a program that displays an AVL tree along with its balance fac.docx
 Write a program that displays an AVL tree  along with its balance fac.docx Write a program that displays an AVL tree  along with its balance fac.docx
Write a program that displays an AVL tree along with its balance fac.docx
 
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdfA)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
 
Write a function in C++ to generate an N-node random binary search t.pdf
Write a function in C++ to generate an N-node random binary search t.pdfWrite a function in C++ to generate an N-node random binary search t.pdf
Write a function in C++ to generate an N-node random binary search t.pdf
 
Given the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdfGiven the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdf
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 

More from shanki7

I cant see the question .pdf
                     I cant see the question                        .pdf                     I cant see the question                        .pdf
I cant see the question .pdfshanki7
 
sulfur trioxide is SO3 atomic mass S = 32.1 gmo.pdf
                     sulfur trioxide is SO3 atomic mass S = 32.1 gmo.pdf                     sulfur trioxide is SO3 atomic mass S = 32.1 gmo.pdf
sulfur trioxide is SO3 atomic mass S = 32.1 gmo.pdfshanki7
 
x2 = 7xSolutionx2 = 7x.pdf
x2 = 7xSolutionx2 = 7x.pdfx2 = 7xSolutionx2 = 7x.pdf
x2 = 7xSolutionx2 = 7x.pdfshanki7
 
vrms=3RTMxSolutionvrms=3RTMx.pdf
vrms=3RTMxSolutionvrms=3RTMx.pdfvrms=3RTMxSolutionvrms=3RTMx.pdf
vrms=3RTMxSolutionvrms=3RTMx.pdfshanki7
 
This program here prints the number of words that occurs in the inpu.pdf
This program here prints the number of words that occurs in the inpu.pdfThis program here prints the number of words that occurs in the inpu.pdf
This program here prints the number of words that occurs in the inpu.pdfshanki7
 
This is a heart related disease. The identification of a disease.pdf
This is a heart related disease. The identification of a disease.pdfThis is a heart related disease. The identification of a disease.pdf
This is a heart related disease. The identification of a disease.pdfshanki7
 
The terminating hairpin loop occurs in the tryptophan operon whe.pdf
The terminating hairpin loop occurs in the tryptophan operon whe.pdfThe terminating hairpin loop occurs in the tryptophan operon whe.pdf
The terminating hairpin loop occurs in the tryptophan operon whe.pdfshanki7
 
The solution is--fn= -13(-1)n+ 13(2)nSolutionThe solution .pdf
The solution is--fn= -13(-1)n+ 13(2)nSolutionThe solution .pdfThe solution is--fn= -13(-1)n+ 13(2)nSolutionThe solution .pdf
The solution is--fn= -13(-1)n+ 13(2)nSolutionThe solution .pdfshanki7
 
The follow list restates these 3 fundamental levels of service for Q.pdf
The follow list restates these 3 fundamental levels of service for Q.pdfThe follow list restates these 3 fundamental levels of service for Q.pdf
The follow list restates these 3 fundamental levels of service for Q.pdfshanki7
 
Please find the answers and explanations belowPart A1. The ing.pdf
Please find the answers and explanations belowPart A1. The ing.pdfPlease find the answers and explanations belowPart A1. The ing.pdf
Please find the answers and explanations belowPart A1. The ing.pdfshanki7
 
nSolutionn.pdf
nSolutionn.pdfnSolutionn.pdf
nSolutionn.pdfshanki7
 
Mass of liquid = 22.5 gHeat added = 2.34 kJ = 2340 JTemperature .pdf
Mass of liquid = 22.5 gHeat added = 2.34 kJ = 2340 JTemperature .pdfMass of liquid = 22.5 gHeat added = 2.34 kJ = 2340 JTemperature .pdf
Mass of liquid = 22.5 gHeat added = 2.34 kJ = 2340 JTemperature .pdfshanki7
 
It is given that we should use 4 bit input, i.e we will have a set o.pdf
It is given that we should use 4 bit input, i.e we will have a set o.pdfIt is given that we should use 4 bit input, i.e we will have a set o.pdf
It is given that we should use 4 bit input, i.e we will have a set o.pdfshanki7
 
IndexingConcatinationSolutionIndexingConcatination.pdf
IndexingConcatinationSolutionIndexingConcatination.pdfIndexingConcatinationSolutionIndexingConcatination.pdf
IndexingConcatinationSolutionIndexingConcatination.pdfshanki7
 
import java.util.ArrayList; import java.util.List;public class H.pdf
import java.util.ArrayList; import java.util.List;public class H.pdfimport java.util.ArrayList; import java.util.List;public class H.pdf
import java.util.ArrayList; import java.util.List;public class H.pdfshanki7
 
i dont knowSolutioni dont know.pdf
i dont knowSolutioni dont know.pdfi dont knowSolutioni dont know.pdf
i dont knowSolutioni dont know.pdfshanki7
 
Heterochromatin is a tightly packed form of DNA, which comes in mult.pdf
Heterochromatin is a tightly packed form of DNA, which comes in mult.pdfHeterochromatin is a tightly packed form of DNA, which comes in mult.pdf
Heterochromatin is a tightly packed form of DNA, which comes in mult.pdfshanki7
 
H2A (ACID) Molarity         =    0.15 M Normality N1 =    Mo.pdf
H2A (ACID) Molarity         =    0.15 M Normality N1 =    Mo.pdfH2A (ACID) Molarity         =    0.15 M Normality N1 =    Mo.pdf
H2A (ACID) Molarity         =    0.15 M Normality N1 =    Mo.pdfshanki7
 
False , we should not always rename the worksheet.SolutionFals.pdf
False , we should not always rename the worksheet.SolutionFals.pdfFalse , we should not always rename the worksheet.SolutionFals.pdf
False , we should not always rename the worksheet.SolutionFals.pdfshanki7
 
Difference between computer architecture and computer organization.pdf
Difference between computer architecture and computer organization.pdfDifference between computer architecture and computer organization.pdf
Difference between computer architecture and computer organization.pdfshanki7
 

More from shanki7 (20)

I cant see the question .pdf
                     I cant see the question                        .pdf                     I cant see the question                        .pdf
I cant see the question .pdf
 
sulfur trioxide is SO3 atomic mass S = 32.1 gmo.pdf
                     sulfur trioxide is SO3 atomic mass S = 32.1 gmo.pdf                     sulfur trioxide is SO3 atomic mass S = 32.1 gmo.pdf
sulfur trioxide is SO3 atomic mass S = 32.1 gmo.pdf
 
x2 = 7xSolutionx2 = 7x.pdf
x2 = 7xSolutionx2 = 7x.pdfx2 = 7xSolutionx2 = 7x.pdf
x2 = 7xSolutionx2 = 7x.pdf
 
vrms=3RTMxSolutionvrms=3RTMx.pdf
vrms=3RTMxSolutionvrms=3RTMx.pdfvrms=3RTMxSolutionvrms=3RTMx.pdf
vrms=3RTMxSolutionvrms=3RTMx.pdf
 
This program here prints the number of words that occurs in the inpu.pdf
This program here prints the number of words that occurs in the inpu.pdfThis program here prints the number of words that occurs in the inpu.pdf
This program here prints the number of words that occurs in the inpu.pdf
 
This is a heart related disease. The identification of a disease.pdf
This is a heart related disease. The identification of a disease.pdfThis is a heart related disease. The identification of a disease.pdf
This is a heart related disease. The identification of a disease.pdf
 
The terminating hairpin loop occurs in the tryptophan operon whe.pdf
The terminating hairpin loop occurs in the tryptophan operon whe.pdfThe terminating hairpin loop occurs in the tryptophan operon whe.pdf
The terminating hairpin loop occurs in the tryptophan operon whe.pdf
 
The solution is--fn= -13(-1)n+ 13(2)nSolutionThe solution .pdf
The solution is--fn= -13(-1)n+ 13(2)nSolutionThe solution .pdfThe solution is--fn= -13(-1)n+ 13(2)nSolutionThe solution .pdf
The solution is--fn= -13(-1)n+ 13(2)nSolutionThe solution .pdf
 
The follow list restates these 3 fundamental levels of service for Q.pdf
The follow list restates these 3 fundamental levels of service for Q.pdfThe follow list restates these 3 fundamental levels of service for Q.pdf
The follow list restates these 3 fundamental levels of service for Q.pdf
 
Please find the answers and explanations belowPart A1. The ing.pdf
Please find the answers and explanations belowPart A1. The ing.pdfPlease find the answers and explanations belowPart A1. The ing.pdf
Please find the answers and explanations belowPart A1. The ing.pdf
 
nSolutionn.pdf
nSolutionn.pdfnSolutionn.pdf
nSolutionn.pdf
 
Mass of liquid = 22.5 gHeat added = 2.34 kJ = 2340 JTemperature .pdf
Mass of liquid = 22.5 gHeat added = 2.34 kJ = 2340 JTemperature .pdfMass of liquid = 22.5 gHeat added = 2.34 kJ = 2340 JTemperature .pdf
Mass of liquid = 22.5 gHeat added = 2.34 kJ = 2340 JTemperature .pdf
 
It is given that we should use 4 bit input, i.e we will have a set o.pdf
It is given that we should use 4 bit input, i.e we will have a set o.pdfIt is given that we should use 4 bit input, i.e we will have a set o.pdf
It is given that we should use 4 bit input, i.e we will have a set o.pdf
 
IndexingConcatinationSolutionIndexingConcatination.pdf
IndexingConcatinationSolutionIndexingConcatination.pdfIndexingConcatinationSolutionIndexingConcatination.pdf
IndexingConcatinationSolutionIndexingConcatination.pdf
 
import java.util.ArrayList; import java.util.List;public class H.pdf
import java.util.ArrayList; import java.util.List;public class H.pdfimport java.util.ArrayList; import java.util.List;public class H.pdf
import java.util.ArrayList; import java.util.List;public class H.pdf
 
i dont knowSolutioni dont know.pdf
i dont knowSolutioni dont know.pdfi dont knowSolutioni dont know.pdf
i dont knowSolutioni dont know.pdf
 
Heterochromatin is a tightly packed form of DNA, which comes in mult.pdf
Heterochromatin is a tightly packed form of DNA, which comes in mult.pdfHeterochromatin is a tightly packed form of DNA, which comes in mult.pdf
Heterochromatin is a tightly packed form of DNA, which comes in mult.pdf
 
H2A (ACID) Molarity         =    0.15 M Normality N1 =    Mo.pdf
H2A (ACID) Molarity         =    0.15 M Normality N1 =    Mo.pdfH2A (ACID) Molarity         =    0.15 M Normality N1 =    Mo.pdf
H2A (ACID) Molarity         =    0.15 M Normality N1 =    Mo.pdf
 
False , we should not always rename the worksheet.SolutionFals.pdf
False , we should not always rename the worksheet.SolutionFals.pdfFalse , we should not always rename the worksheet.SolutionFals.pdf
False , we should not always rename the worksheet.SolutionFals.pdf
 
Difference between computer architecture and computer organization.pdf
Difference between computer architecture and computer organization.pdfDifference between computer architecture and computer organization.pdf
Difference between computer architecture and computer organization.pdf
 

Recently uploaded

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxAmita Gupta
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 

Recently uploaded (20)

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 

Please read the comment ins codeExpressionTree.java-------------.pdf

  • 1. Please read the comment ins code ExpressionTree.java ---------------------------------- /** * This is the class for Expression Tree. * Used to create Expression Tree and Evaluate it */ /** * Following logic is used to construct a Tree * Here we use stack for Preparing Tree * Loop through given Expression String * If Character is Operand , Create node and push to stack * If Character is Operator then * 1)Create Node for Operator * 2)Pop 2 nodes from Stack and Made * OpretorNode--> left == first node pop * OpretorNode--> right == second node pop * At the end of creation of Expression Tree, Stack have only one node , which is root of Expression tree */ /** Class ExpressionTree **/ class ExpressionTree { /** class TreeNode * Stored Character ==> Digit(0..9) or a Operator +,-,*,/ * Left Node and Right Node * * **/ class TreeNode { char data; TreeNode left, right; /** constructor **/
  • 2. public TreeNode(char data) { this.data = data; this.left = null; this.right = null; } } /** class StackNode **/ class StackNode { TreeNode treeNode; StackNode next; /** constructor **/ public StackNode(TreeNode treeNode) { this.treeNode = treeNode; next = null; } } private static StackNode top; /** constructor * Constructor takes input string like "+-+7*935*82*625" * Input should be in Prefix notation * **/ public ExpressionTree(String expression) { top = null; //Call Method for prepare expression tree buildTree(expression); } /** function to clear tree **/ public void clear() { top = null; } /** function to push a node **/
  • 3. private void push(TreeNode ptr) { if (top == null) top = new StackNode(ptr); else { StackNode nptr = new StackNode(ptr); nptr.next = top; top = nptr; } } /** function to pop a node * When it find operator pop 2 elements from Stack * * **/ private TreeNode pop() { if (top == null) throw new RuntimeException("Underflow"); else { TreeNode ptr = top.treeNode; top = top.next; return ptr; } } /** function to get top node **/ private TreeNode peek() { return top.treeNode; } /** function to insert character **/ private void insert(char val) { try {
  • 4. //If Operand , Create node and push to Stack if (isDigit(val)) { TreeNode nptr = new TreeNode(val); push(nptr); } //If Operator , Create node and popup 2 elements and make them its right and left else if (isOperator(val)) { TreeNode nptr = new TreeNode(val); nptr.left = pop(); nptr.right = pop(); push(nptr); } } catch (Exception e) { System.out.println("Invalid Expression"); } } /** function to check if digit **/ private boolean isDigit(char ch) { return ch >= '0' && ch <= '9'; } /** function to check if operator **/ private boolean isOperator(char ch) { return ch == '+' || ch == '-' || ch == '*' || ch == '/'; } /** function to convert character to digit **/ private int toDigit(char ch) { return ch - '0'; } /** function to build tree from input */
  • 5. public void buildTree(String eqn) { for (int i = eqn.length() - 1; i >= 0; i--) insert(eqn.charAt(i)); } /** function to evaluate tree */ public double evaluate() { return evaluate(peek()); } /** function to evaluate tree * * */ public double evaluate(TreeNode ptr) { if (ptr.left == null && ptr.right == null) return toDigit(ptr.data); else { double result = 0.0; double left = evaluate(ptr.left); double right = evaluate(ptr.right); char operator = ptr.data; switch (operator) { case '+' : result = left + right; break; case '-' : result = left - right; break; case '*' : result = left * right; break; case '/' : result = left / right; break; default : result = left + right; break; } return result; } } /** function to get postfix expression */ public void postfix()
  • 6. { postOrder(peek()); } /** post order traversal */ private void postOrder(TreeNode ptr) { if (ptr != null) { postOrder(ptr.left); postOrder(ptr.right); System.out.print(ptr.data); } } /** function to get infix expression */ public void infix() { inOrder(peek()); } /** in order traversal */ private void inOrder(TreeNode ptr) { if (ptr != null) { inOrder(ptr.left); System.out.print(ptr.data); inOrder(ptr.right); } } /** function to get prefix expression */ public void prefix() { preOrder(peek()); } /** pre order traversal */ private void preOrder(TreeNode ptr) {
  • 7. if (ptr != null) { System.out.print(ptr.data); preOrder(ptr.left); preOrder(ptr.right); } } } ExpressionTreeTest.java , class to test ------------------------------------------------------------ import java.util.Scanner; /** class ExpressionTreeTest **/ public class ExpressionTreeTest { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Expression Tree Test"); System.out.println(" Enter equation in prefix form"); /** make object of ExpressionTree **/ ExpressionTree et = new ExpressionTree(scan.next()); System.out.print(" Prefix : "); et.prefix(); System.out.print(" Infix : "); et.infix(); System.out.print(" Postfix : "); et.postfix(); System.out.println(" Evaluated Result : "+ et.evaluate()); } } Solution
  • 8. Please read the comment ins code ExpressionTree.java ---------------------------------- /** * This is the class for Expression Tree. * Used to create Expression Tree and Evaluate it */ /** * Following logic is used to construct a Tree * Here we use stack for Preparing Tree * Loop through given Expression String * If Character is Operand , Create node and push to stack * If Character is Operator then * 1)Create Node for Operator * 2)Pop 2 nodes from Stack and Made * OpretorNode--> left == first node pop * OpretorNode--> right == second node pop * At the end of creation of Expression Tree, Stack have only one node , which is root of Expression tree */ /** Class ExpressionTree **/ class ExpressionTree { /** class TreeNode * Stored Character ==> Digit(0..9) or a Operator +,-,*,/ * Left Node and Right Node * * **/ class TreeNode { char data; TreeNode left, right; /** constructor **/ public TreeNode(char data)
  • 9. { this.data = data; this.left = null; this.right = null; } } /** class StackNode **/ class StackNode { TreeNode treeNode; StackNode next; /** constructor **/ public StackNode(TreeNode treeNode) { this.treeNode = treeNode; next = null; } } private static StackNode top; /** constructor * Constructor takes input string like "+-+7*935*82*625" * Input should be in Prefix notation * **/ public ExpressionTree(String expression) { top = null; //Call Method for prepare expression tree buildTree(expression); } /** function to clear tree **/ public void clear() { top = null; } /** function to push a node **/ private void push(TreeNode ptr)
  • 10. { if (top == null) top = new StackNode(ptr); else { StackNode nptr = new StackNode(ptr); nptr.next = top; top = nptr; } } /** function to pop a node * When it find operator pop 2 elements from Stack * * **/ private TreeNode pop() { if (top == null) throw new RuntimeException("Underflow"); else { TreeNode ptr = top.treeNode; top = top.next; return ptr; } } /** function to get top node **/ private TreeNode peek() { return top.treeNode; } /** function to insert character **/ private void insert(char val) { try { //If Operand , Create node and push to Stack
  • 11. if (isDigit(val)) { TreeNode nptr = new TreeNode(val); push(nptr); } //If Operator , Create node and popup 2 elements and make them its right and left else if (isOperator(val)) { TreeNode nptr = new TreeNode(val); nptr.left = pop(); nptr.right = pop(); push(nptr); } } catch (Exception e) { System.out.println("Invalid Expression"); } } /** function to check if digit **/ private boolean isDigit(char ch) { return ch >= '0' && ch <= '9'; } /** function to check if operator **/ private boolean isOperator(char ch) { return ch == '+' || ch == '-' || ch == '*' || ch == '/'; } /** function to convert character to digit **/ private int toDigit(char ch) { return ch - '0'; } /** function to build tree from input */ public void buildTree(String eqn)
  • 12. { for (int i = eqn.length() - 1; i >= 0; i--) insert(eqn.charAt(i)); } /** function to evaluate tree */ public double evaluate() { return evaluate(peek()); } /** function to evaluate tree * * */ public double evaluate(TreeNode ptr) { if (ptr.left == null && ptr.right == null) return toDigit(ptr.data); else { double result = 0.0; double left = evaluate(ptr.left); double right = evaluate(ptr.right); char operator = ptr.data; switch (operator) { case '+' : result = left + right; break; case '-' : result = left - right; break; case '*' : result = left * right; break; case '/' : result = left / right; break; default : result = left + right; break; } return result; } } /** function to get postfix expression */ public void postfix() {
  • 13. postOrder(peek()); } /** post order traversal */ private void postOrder(TreeNode ptr) { if (ptr != null) { postOrder(ptr.left); postOrder(ptr.right); System.out.print(ptr.data); } } /** function to get infix expression */ public void infix() { inOrder(peek()); } /** in order traversal */ private void inOrder(TreeNode ptr) { if (ptr != null) { inOrder(ptr.left); System.out.print(ptr.data); inOrder(ptr.right); } } /** function to get prefix expression */ public void prefix() { preOrder(peek()); } /** pre order traversal */ private void preOrder(TreeNode ptr) { if (ptr != null)
  • 14. { System.out.print(ptr.data); preOrder(ptr.left); preOrder(ptr.right); } } } ExpressionTreeTest.java , class to test ------------------------------------------------------------ import java.util.Scanner; /** class ExpressionTreeTest **/ public class ExpressionTreeTest { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Expression Tree Test"); System.out.println(" Enter equation in prefix form"); /** make object of ExpressionTree **/ ExpressionTree et = new ExpressionTree(scan.next()); System.out.print(" Prefix : "); et.prefix(); System.out.print(" Infix : "); et.infix(); System.out.print(" Postfix : "); et.postfix(); System.out.println(" Evaluated Result : "+ et.evaluate()); } }