PPT5 - Introduction To Tree, Binary Tree and Expression Tree
PPT5 - Introduction To Tree, Binary Tree and Expression Tree
- -
* D / *
+ C A B + D
A B B C
Type of Binary Tree
• PERFECT binary tree is a binary tree in which every level are at
the same depth.
In some
literatures,
level of binary
tree
starts with 1
(root).
Property of Binary
Tree
• Maximum number of nodes on a binary tree of height
h is 2h+1 - 1.
Maximum nodes
of a binary tree of
height 3
=1+2+4+8
= 20 + 21 + 22 + 23
= 24 – 1
= 15
Property of Binary
Tree
• Minimum height of a binary tree of n nodes is 2log(n).
• Maximum height of a binary tree of n nodes is n - 1.
• Prefix : *+ab/-cde
• Postfix: ab+cd-e/*
• Infix : (a+b)*((c-d)/e)
Expression Tree
Concept
• We will use this structure for each node in the tree:
struct tnode {
char chr;
struct tnode *left;
struct tnode *right;
};
• It is a binary tree.
Create Expression
Tree from Prefix
• We can create an expression tree from a prefix by
recursive.
main function
struct tnode *root = newnode(s[0]);
char s[MAXN];
f(root);
int p = 0;
• Prefix : *+abc
• Postfix : ab+c*
• Wrong infix: a+b*c
• Correct infix : (a+b)*c
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( ')' );
}