COMP6458 - Struktur Data Pert5 - Introduction To Tree - Binary Tree and Expression Tree
COMP6458 - Struktur Data Pert5 - Introduction To Tree - Binary Tree and Expression Tree
Year : 2016
Introduction to Tree,
Binary Tree And Expression Tree
Learning Outcomes
2
Sub Topics
3
Tree Concept
DEGREE of TREE = 3
LEVEL 1 A DEGREE of C = 2
HEIGHT = 3
LEVEL 2 B C D PARENT of C = A
CHILDREN of A = B, C, D
SIBILING of F = G
LEVEL 3 E F G ANCESTOR of F = A, C
DESCENDANT of C = F, G
TREE
4
Tree Concept
5
Binary Tree Concept
6
Binary Tree Concept
7
Type of Binary Tree
8
PERFECT Binary Tree
9
COMPLETE Binary Tree
10
SKEWED Binary Tree
11
Property of Binary Tree
In some
literatures,
level of binary
tree
starts with 1
(root).
12
Property of Binary Tree
Maximum nodes
of a binary tree of
height 3
=1+2+4+8
= 20 + 21 + 22 + 23
= 24 – 1
= 15
13
Property of Binary Tree
14
Representation of Binary Tree
struct node {
int data;
struct node *left;
struct node *right;
struct node *parent;
};
16
Expression Tree Concept
17
Expression Tree Concept
Prefix : *+ab/-cde
Postfix : ab+cd-e/*
Infix : (a+b)*((c-d)/e)
18
Expression Tree Concept
struct tnode {
char chr;
struct tnode *left;
struct tnode *right;
};
It is a binary tree.
19
Create Expression Tree from Prefix
main function
char s[MAXN]; struct tnode *root = newnode(s[0]);
int p = 0; f(root);
20
Prefix Traversal
21
Postfix Traversal
22
Infix Traversal
23
Infix Traversal
It’s seems right, but infix may have operator precedence ambiguity
without brackets.
24
Infix Traversal
Prefix : *+abc
Postfix : ab+c*
Wrong infix : a+b*c
Correct infix : (a+b)*c
25
Infix Traversal
To fix that, we can add brackets () when expanding an operator.
void infix(tnode *curr) {
if ( is_operator(curr->chr) ) putchar( '(' );
if ( curr->left != 0 ) infix(curr->left);
printf( "%c", curr->chr );
if ( curr->right != 0 ) infix(curr->right);
if ( is_operator(curr->chr) ) putchar( ')' );
}
26
Create Exp-Tree from Postfix
Now, can you create an expression tree given a postfix
notation?
27
Summary
28
Summary
29
References
30
END
Introduction to Tree, Binary Tree and Expression Tree
31