SlideShare a Scribd company logo
Data Structure
Lecture No. 14
Binary Expression Tree
Engr. Rashid Farid Chishti
http://youtube.com/rfchishti
http://sites.google.com/site/chishti
International Islamic University H-10, Islamabad, Pakistan
Video Lecture
 Expression trees are binary trees for mathematical expression
 Leaves are operands (a, b, c, …)
 Other nodes are operators. (+, -, *, /)
 This is Expression Tree for
(a+b*c)+((d*e+f)*g)
Binary Expression Tree
+
+
*
b
a
c
*
+ g
f
*
d e
 Preorder traversal: (node, left, right) gives Prefix Expression.
+ + a * b c * + * d e f g
Expression Tree Traversal
+
+
*
b
a
c
*
+ g
f
*
d e
 Inorder traversal: (left, node, right) gives Infix Expression.
a + b * c + d * e + f * g
Expression Tree Traversal
+
+
*
b
a
c
*
+ g
f
*
d e
 Postorder traversal: (left, right, node) gives Postfix Expression.
a b c * + d e * f + g * +
Expression Tree Traversal
+
+
*
b
a
c
*
+ g
f
*
d e
 Read expression one symbol at a time
 If the symbol is an operand
 Create a one-node tree
 Push its pointer to a stack
 If the symbol is an operator
 Pop two pointers
 Form a new tree whose root is the operator
 In the end, the only element of the stack will be the root of an expression tree.
Constructing a Binary Expression Tree from Postfix
 a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
 a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
a
 a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
a b
 a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
b
+
a
 a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
b
+
a
c
 a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
b
+
a
c d
 a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
b
+
a
c d e
 a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
b
+
a
c
e
+
d
 a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
b
+
a
*
c
e
+
d
 a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
*
*
c
e
+
d
b
*
a
 a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
*
*
c
e
+
d
b
*
a
root
(1+2) * ((3*(4+5))
Evaluation of a Binary Expression Tree
*
*
3
5
+
4
2
+
1
root
3
9
27
81
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
struct Data{
char opr;
double num;
};
struct Tree_Node {
Tree_Node* left ;
Data data ;
Tree_Node* right ;
};
typedef Tree_Node* SType;
19
Implementation of Binary Expression Tree
struct Node{
SType info ;
Node *next ;
};
class Stack{
private :
Node* head;
public :
Stack( );
bool Is_Empty();
SType Top();
void Push ( SType Data );
SType Pop ( );
~Stack( ) ;
};
Stack::Stack( ){
head = NULL;
}
1 2
bool Stack::Is_Empty() {
return head == NULL;
}
SType Stack::Top() {
if ( !Is_Empty() )
return head->info;
return NULL;
}
void Stack :: Push ( SType Data ) {
Node *newNode ;
newNode = new Node ;
if ( newNode == NULL ){
cout << endl << "Stack is full" ;
return;
}
newNode -> info = Data ;
newNode -> next = head ; head = newNode;
}
20
Implementation of Binary Expression Tree
SType Stack :: Pop( ) {
if ( Is_Empty() ){
cout << "Stack is empty " ;
return NULL ;
}
Node *current ;
SType Data ;
current = head ;
Data = current -> info ;
head = head -> next ;
delete current ;
return Data ;
}
Stack :: ~Stack( ){
Node *current ;
while ( head != NULL ){
current = head ;
head = head -> next ; delete head ;
}
}
3 4
class Binary_Expression_Tree{
private:
Stack St;
Tree_Node* root;
Tree_Node* t,*t1,*t2;
void Pre_Order(Tree_Node* );
void In_Order(Tree_Node* );
void Post_Order(Tree_Node* );
bool Is_Operator(char c);
Tree_Node* New_Tree_Node(Data d);
double Evaluate (Tree_Node* node);
public:
Binary_Expression_Tree(){root = NULL;};
Binary_Expression_Tree(char Postfix[]);
double Evaluate( );
void Pre_Order ( );
void In_Order ( );
void Post_Order( );
};
21
Implementation of Binary Expression Tree
Tree_Node* Binary_Expression_Tree ::
New_Tree_Node(Data d){
Tree_Node* temp = new Tree_Node;
temp->left = NULL; temp->right = NULL;
temp->data = d;
return temp;
};
bool Binary_Expression_Tree ::
Is_Operator(char c){
switch(c){
case '+': return true;
case '-': return true;
case '*': return true;
case '/': return true;
case '^': return true;
default : return false;
}
return false;
}
5 6
Binary_Expression_Tree ::
Binary_Expression_Tree(char Postfix[]){
// Traverse through every character of
// input expression
for (int i=0; Postfix[i]; i++) {
// ignore space and tab
if( Postfix[i] == ' ' ||
Postfix[i] == 't')
continue;
// If operand, simply push into stack
if (!Is_Operator(Postfix[i])) {
Data d;
d.num = Postfix[i] - 0x30;
d.opr = 0;
t = New_Tree_Node(d);
St.Push(t);
}
22
Implementation of Binary Expression Tree
else { // operator
Data d;
d.num = 0;
d.opr = Postfix[i];
t = New_Tree_Node(d);
// Pop two top nodes
t1 = St.Pop(); // Remove top
t2 = St.Pop();
// make them children
t->right = t1;
t->left = t2;
// Add this subexpression to stack
St.Push(t);
}
}
// connect it with root pointer
root = St.Pop();
}
7 8
double Binary_Expression_Tree ::
Evaluate ( ) {
return Evaluate(root);
}
double Binary_Expression_Tree ::
Evaluate (Tree_Node* node) {
// empty tree
if (node == NULL)
return 0;
// leaf node i.e, an integer
if (node->left == NULL &&
node->right== NULL) {
return node->data.num;
}
23
Implementation of Binary Expression Tree
// Evaluate left subtree
double l_val = Evaluate(node->left);
// Evaluate right subtree
double r_val = Evaluate(node->right);
// Check which operator to apply
if (node->data.opr == '+')
return l_val + r_val;
if (node->data.opr == '-')
return l_val-r_val;
if (node->data.opr == '*')
return l_val*r_val;
if (node->data.opr == '/' )
return l_val/r_val;
if (node->data.opr == '^')
return pow(l_val,r_val);
return 0;
}
9 10
void Binary_Expression_Tree :: Pre_Order(){
Pre_Order(root);
}
void Binary_Expression_Tree ::
Pre_Order(Tree_Node *node){
if(node != NULL){
if (node->data.opr == 0)
cout << node->data.num << " ";
else
cout << node->data.opr << " ";
Pre_Order(node->left);
Pre_Order(node->right);
}
}
24
Implementation of Binary Expression Tree
void Binary_Expression_Tree :: In_Order ( ){
In_Order(root);
}
void Binary_Expression_Tree ::
In_Order(Tree_Node *node){
if(node != NULL){
In_Order(node->left);
if (node->data.opr == 0)
cout << node->data.num << " ";
else
cout << node->data.opr << " ";
In_Order(node->right);
}
}
11 12
void Binary_Expression_Tree :: Post_Order(){
Post_Order(root);
}
void Binary_Expression_Tree ::
Post_Order(Tree_Node *node){
if(node != NULL){
Post_Order(node->left);
Post_Order(node->right);
if (node->data.opr == 0)
cout << node->data.num << " ";
else
cout << node->data.opr << " ";
}
}
25
Implementation of Binary Expression Tree
int main(){
Binary_Expression_Tree
BET("1 2 + 3 4 5 + * *");
cout <<" -:Pre_Order Traversal:-n";
BET.Pre_Order();
cout <<"nn -:In_Order Traversal:-n";
BET.In_Order();
cout << endl;
cout <<"nn-:Post_Order Traversal:-n";
BET.Post_Order();
cout << endl;
cout << "Answer = "<< BET.Evaluate();
cout << endl;
system("PAUSE"); return 0;
}
13 14
Program Output

More Related Content

Similar to Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx

#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx
ajoy21
 
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
arihantelehyb
 
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
arjuncorner565
 
CS50 Lecture4
CS50 Lecture4CS50 Lecture4
CS50 Lecture4
昀 李
 
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
anton291
 
For this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docxFor this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docx
budbarber38650
 
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
illyasraja7
 
Admissions in india 2015
Admissions in india 2015Admissions in india 2015
Admissions in india 2015
Edhole.com
 
Trees
TreesTrees
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
ZarghamullahShah
 
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docxAvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
rock73
 
DS Code (CWH).docx
DS Code (CWH).docxDS Code (CWH).docx
DS Code (CWH).docx
KamalSaini561034
 
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf
arihantmobileselepun
 
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptxData Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
RashidFaridChishti
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
Han Lee
 
Help to implement delete_node get_succ get_pred walk and.pdf
Help to implement delete_node get_succ get_pred walk and.pdfHelp to implement delete_node get_succ get_pred walk and.pdf
Help to implement delete_node get_succ get_pred walk and.pdf
contact32
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
Jussi Pohjolainen
 
I have C++ question that I do not know how to do, Can you teach me t.pdf
I have C++ question that I do not know how to do, Can you teach me t.pdfI have C++ question that I do not know how to do, Can you teach me t.pdf
I have C++ question that I do not know how to do, Can you teach me t.pdf
fasttrackscardecors
 
hi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfhi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdf
archgeetsenterprises
 
I need to implment a function that can reverse a single linked list..pdf
I need to implment a function that can reverse a single linked list..pdfI need to implment a function that can reverse a single linked list..pdf
I need to implment a function that can reverse a single linked list..pdf
rohit219406
 

Similar to Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx (20)

#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx
 
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.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.pdf
 
CS50 Lecture4
CS50 Lecture4CS50 Lecture4
CS50 Lecture4
 
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
 
For this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docxFor this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docx
 
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
 
Admissions in india 2015
Admissions in india 2015Admissions in india 2015
Admissions in india 2015
 
Trees
TreesTrees
Trees
 
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
 
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docxAvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
 
DS Code (CWH).docx
DS Code (CWH).docxDS Code (CWH).docx
DS Code (CWH).docx
 
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf
 
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptxData Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
 
Help to implement delete_node get_succ get_pred walk and.pdf
Help to implement delete_node get_succ get_pred walk and.pdfHelp to implement delete_node get_succ get_pred walk and.pdf
Help to implement delete_node get_succ get_pred walk and.pdf
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
I have C++ question that I do not know how to do, Can you teach me t.pdf
I have C++ question that I do not know how to do, Can you teach me t.pdfI have C++ question that I do not know how to do, Can you teach me t.pdf
I have C++ question that I do not know how to do, Can you teach me t.pdf
 
hi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfhi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdf
 
I need to implment a function that can reverse a single linked list..pdf
I need to implment a function that can reverse a single linked list..pdfI need to implment a function that can reverse a single linked list..pdf
I need to implment a function that can reverse a single linked list..pdf
 

More from RashidFaridChishti

Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxLab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
RashidFaridChishti
 
Object Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docxObject Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docx
RashidFaridChishti
 
Lab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docxLab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docx
RashidFaridChishti
 
Data Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptxData Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptxData Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptxData Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptxData Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptxData Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptxData Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptxData Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptxData Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptxData Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptxData Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptxData Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptxData Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptxData Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptxData Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptx
RashidFaridChishti
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
RashidFaridChishti
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
RashidFaridChishti
 
Object Oriented Programming using C++: Ch10 Pointers.pptx
Object Oriented Programming using C++: Ch10 Pointers.pptxObject Oriented Programming using C++: Ch10 Pointers.pptx
Object Oriented Programming using C++: Ch10 Pointers.pptx
RashidFaridChishti
 

More from RashidFaridChishti (20)

Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxLab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
 
Object Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docxObject Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docx
 
Lab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docxLab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docx
 
Data Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptxData Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptx
 
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptxData Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptxData Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptx
 
Data Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptxData Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptx
 
Data Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptxData Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptx
 
Data Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptxData Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptx
 
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptxData Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
 
Data Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptxData Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptx
 
Data Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptxData Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptx
 
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptxData Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
 
Data Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptxData Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptx
 
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptxData Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
 
Data Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptxData Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptx
 
Data Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptxData Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptx
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
 
Object Oriented Programming using C++: Ch10 Pointers.pptx
Object Oriented Programming using C++: Ch10 Pointers.pptxObject Oriented Programming using C++: Ch10 Pointers.pptx
Object Oriented Programming using C++: Ch10 Pointers.pptx
 

Recently uploaded

Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
IJECEIAES
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
ihlasbinance2003
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Textile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdfTextile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdf
NazakatAliKhoso2
 
CSM Cloud Service Management Presentarion
CSM Cloud Service Management PresentarionCSM Cloud Service Management Presentarion
CSM Cloud Service Management Presentarion
rpskprasana
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
wisnuprabawa3
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdfIron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
RadiNasr
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
jpsjournal1
 
Question paper of renewable energy sources
Question paper of renewable energy sourcesQuestion paper of renewable energy sources
Question paper of renewable energy sources
mahammadsalmanmech
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
KrishnaveniKrishnara1
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
NidhalKahouli2
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Textile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdfTextile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdf
 
CSM Cloud Service Management Presentarion
CSM Cloud Service Management PresentarionCSM Cloud Service Management Presentarion
CSM Cloud Service Management Presentarion
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdfIron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
 
Question paper of renewable energy sources
Question paper of renewable energy sourcesQuestion paper of renewable energy sources
Question paper of renewable energy sources
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 

Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx

  • 1. Data Structure Lecture No. 14 Binary Expression Tree Engr. Rashid Farid Chishti http://youtube.com/rfchishti http://sites.google.com/site/chishti International Islamic University H-10, Islamabad, Pakistan Video Lecture
  • 2.  Expression trees are binary trees for mathematical expression  Leaves are operands (a, b, c, …)  Other nodes are operators. (+, -, *, /)  This is Expression Tree for (a+b*c)+((d*e+f)*g) Binary Expression Tree + + * b a c * + g f * d e
  • 3.  Preorder traversal: (node, left, right) gives Prefix Expression. + + a * b c * + * d e f g Expression Tree Traversal + + * b a c * + g f * d e
  • 4.  Inorder traversal: (left, node, right) gives Infix Expression. a + b * c + d * e + f * g Expression Tree Traversal + + * b a c * + g f * d e
  • 5.  Postorder traversal: (left, right, node) gives Postfix Expression. a b c * + d e * f + g * + Expression Tree Traversal + + * b a c * + g f * d e
  • 6.  Read expression one symbol at a time  If the symbol is an operand  Create a one-node tree  Push its pointer to a stack  If the symbol is an operator  Pop two pointers  Form a new tree whose root is the operator  In the end, the only element of the stack will be the root of an expression tree. Constructing a Binary Expression Tree from Postfix
  • 7.  a b + c d e + * * Constructing Expression Tree from Postfix Stack
  • 8.  a b + c d e + * * Constructing Expression Tree from Postfix Stack a
  • 9.  a b + c d e + * * Constructing Expression Tree from Postfix Stack a b
  • 10.  a b + c d e + * * Constructing Expression Tree from Postfix Stack b + a
  • 11.  a b + c d e + * * Constructing Expression Tree from Postfix Stack b + a c
  • 12.  a b + c d e + * * Constructing Expression Tree from Postfix Stack b + a c d
  • 13.  a b + c d e + * * Constructing Expression Tree from Postfix Stack b + a c d e
  • 14.  a b + c d e + * * Constructing Expression Tree from Postfix Stack b + a c e + d
  • 15.  a b + c d e + * * Constructing Expression Tree from Postfix Stack b + a * c e + d
  • 16.  a b + c d e + * * Constructing Expression Tree from Postfix Stack * * c e + d b * a
  • 17.  a b + c d e + * * Constructing Expression Tree from Postfix Stack * * c e + d b * a root
  • 18. (1+2) * ((3*(4+5)) Evaluation of a Binary Expression Tree * * 3 5 + 4 2 + 1 root 3 9 27 81
  • 19. #include <iostream> #include <string> #include <math.h> using namespace std; struct Data{ char opr; double num; }; struct Tree_Node { Tree_Node* left ; Data data ; Tree_Node* right ; }; typedef Tree_Node* SType; 19 Implementation of Binary Expression Tree struct Node{ SType info ; Node *next ; }; class Stack{ private : Node* head; public : Stack( ); bool Is_Empty(); SType Top(); void Push ( SType Data ); SType Pop ( ); ~Stack( ) ; }; Stack::Stack( ){ head = NULL; } 1 2
  • 20. bool Stack::Is_Empty() { return head == NULL; } SType Stack::Top() { if ( !Is_Empty() ) return head->info; return NULL; } void Stack :: Push ( SType Data ) { Node *newNode ; newNode = new Node ; if ( newNode == NULL ){ cout << endl << "Stack is full" ; return; } newNode -> info = Data ; newNode -> next = head ; head = newNode; } 20 Implementation of Binary Expression Tree SType Stack :: Pop( ) { if ( Is_Empty() ){ cout << "Stack is empty " ; return NULL ; } Node *current ; SType Data ; current = head ; Data = current -> info ; head = head -> next ; delete current ; return Data ; } Stack :: ~Stack( ){ Node *current ; while ( head != NULL ){ current = head ; head = head -> next ; delete head ; } } 3 4
  • 21. class Binary_Expression_Tree{ private: Stack St; Tree_Node* root; Tree_Node* t,*t1,*t2; void Pre_Order(Tree_Node* ); void In_Order(Tree_Node* ); void Post_Order(Tree_Node* ); bool Is_Operator(char c); Tree_Node* New_Tree_Node(Data d); double Evaluate (Tree_Node* node); public: Binary_Expression_Tree(){root = NULL;}; Binary_Expression_Tree(char Postfix[]); double Evaluate( ); void Pre_Order ( ); void In_Order ( ); void Post_Order( ); }; 21 Implementation of Binary Expression Tree Tree_Node* Binary_Expression_Tree :: New_Tree_Node(Data d){ Tree_Node* temp = new Tree_Node; temp->left = NULL; temp->right = NULL; temp->data = d; return temp; }; bool Binary_Expression_Tree :: Is_Operator(char c){ switch(c){ case '+': return true; case '-': return true; case '*': return true; case '/': return true; case '^': return true; default : return false; } return false; } 5 6
  • 22. Binary_Expression_Tree :: Binary_Expression_Tree(char Postfix[]){ // Traverse through every character of // input expression for (int i=0; Postfix[i]; i++) { // ignore space and tab if( Postfix[i] == ' ' || Postfix[i] == 't') continue; // If operand, simply push into stack if (!Is_Operator(Postfix[i])) { Data d; d.num = Postfix[i] - 0x30; d.opr = 0; t = New_Tree_Node(d); St.Push(t); } 22 Implementation of Binary Expression Tree else { // operator Data d; d.num = 0; d.opr = Postfix[i]; t = New_Tree_Node(d); // Pop two top nodes t1 = St.Pop(); // Remove top t2 = St.Pop(); // make them children t->right = t1; t->left = t2; // Add this subexpression to stack St.Push(t); } } // connect it with root pointer root = St.Pop(); } 7 8
  • 23. double Binary_Expression_Tree :: Evaluate ( ) { return Evaluate(root); } double Binary_Expression_Tree :: Evaluate (Tree_Node* node) { // empty tree if (node == NULL) return 0; // leaf node i.e, an integer if (node->left == NULL && node->right== NULL) { return node->data.num; } 23 Implementation of Binary Expression Tree // Evaluate left subtree double l_val = Evaluate(node->left); // Evaluate right subtree double r_val = Evaluate(node->right); // Check which operator to apply if (node->data.opr == '+') return l_val + r_val; if (node->data.opr == '-') return l_val-r_val; if (node->data.opr == '*') return l_val*r_val; if (node->data.opr == '/' ) return l_val/r_val; if (node->data.opr == '^') return pow(l_val,r_val); return 0; } 9 10
  • 24. void Binary_Expression_Tree :: Pre_Order(){ Pre_Order(root); } void Binary_Expression_Tree :: Pre_Order(Tree_Node *node){ if(node != NULL){ if (node->data.opr == 0) cout << node->data.num << " "; else cout << node->data.opr << " "; Pre_Order(node->left); Pre_Order(node->right); } } 24 Implementation of Binary Expression Tree void Binary_Expression_Tree :: In_Order ( ){ In_Order(root); } void Binary_Expression_Tree :: In_Order(Tree_Node *node){ if(node != NULL){ In_Order(node->left); if (node->data.opr == 0) cout << node->data.num << " "; else cout << node->data.opr << " "; In_Order(node->right); } } 11 12
  • 25. void Binary_Expression_Tree :: Post_Order(){ Post_Order(root); } void Binary_Expression_Tree :: Post_Order(Tree_Node *node){ if(node != NULL){ Post_Order(node->left); Post_Order(node->right); if (node->data.opr == 0) cout << node->data.num << " "; else cout << node->data.opr << " "; } } 25 Implementation of Binary Expression Tree int main(){ Binary_Expression_Tree BET("1 2 + 3 4 5 + * *"); cout <<" -:Pre_Order Traversal:-n"; BET.Pre_Order(); cout <<"nn -:In_Order Traversal:-n"; BET.In_Order(); cout << endl; cout <<"nn-:Post_Order Traversal:-n"; BET.Post_Order(); cout << endl; cout << "Answer = "<< BET.Evaluate(); cout << endl; system("PAUSE"); return 0; } 13 14