Trees, Binary Trees, Expression Trees

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 67

Trees, Binary Trees,

Expression Trees
L i n e a r Lists a n d Trees
• Linear lists are useful for serially ordered data
– (e1,e2,e3,…,en)
– Days of week
– Months in a year
– Students in a class
• Trees are useful for hierarchically ordered data
– Joe’s descendants
– Corporate structure
– Government Subdivisions
– Software structure
2
Joe’s Descendants

What are other examples of hierarchically ordered data?

3
4
Definition of Tree
• A tree t is a finite non-empty set of elements
• One of these elements is called the root
• The remaining elements, if any, are
partitioned into trees, which are called the
subtrees of t.

5
Subtrees

6
Tree Terminology
• The element at the top of the
hierarchy is the root.
• Elements next in the hierarchy
are the children of the root.
• Elements next in the hierarchy
are the grandchildren of the
roo and so on.
• Elements at the lowest level of
the hierarchy are the leaves.

7
O t her Definitions
• Leaves, Parent, Grandparent, Siblings,
Ancestors, Descendents
Leaves = {Mike,AI,Sue,Chris}
Parent(Mary) = Joe
Grandparent(Sue) = Mary
Siblings(Mary) = {Ann,John}
Ancestors(Mike) = {Ann,Joe}
Descendents(Mary)={Mark,Sue}

8
Levels a n d H e i g h t
• Root is at level 1 and its children are at level 2.
• Height = depth = number of levels
level 1

level 2

level 3

level 4

9
Node Degree
 Node degree is the number of children it has

10
T ree Degree
 Tree degree is the maximum of node degrees
tree degree = 3

10
Binary Tre e s

12
Binary Tree
• A finite (possibly empty) collection of
elements
• A non-empty binary tree has a root
element and the remaining elements (if
any) are partitioned into two binary trees
• They are called the left and right sub-trees
of the binary tree
T r e e vs. Binary T r e e
• A binary tree may be empty; a tree cannot be empty.
• No node in a binary tree may have a degree more than 2,
whereas there is no limit on the degree of a node in a tree.
• The subtrees of a binary tree are ordered; those of a tree are
not ordered.

a a
o different when viewed as a binary tree
o same when viewed as a tree
b c c b
Binary Tre e for Expressions

15
Binary Tree Properties
1. The drawing of every binary tree with n
elements, n > 0, has exactly n-1 edges.
– Each node has exactly 1 parent (except root)
2. A binary tree of height h, h >= 0, has at least h and at
most 2h-1 elements in it.
‣ At least 1 element at each level  #elements = h
‣ At most 2i-1 elements at i-th level  Σ 2i-1 = 2h -1
a+ar1+ar2+…+ arn-1 = a(rn-1)/(r-1)
Binary Tree Properties
3. The height of a binary tree that contains n elements,
n >= 0, is at least (log2(n+1)) and at most n.
– At least one element at each level  hmax = #elements (n)
– From prev: hmin = ceil(log(n+1))

minimum number of elements maximum number of elements

17
Full B i n a r y T r e e
• A full binary tree of height h has exactly 2h-1 nodes
• Numbering the nodes in a full binary tree
– Number the nodes 1 through 2h-1
– Number by levels from top to bottom
– Within a level, number from left to right

18
Node N u m b e r of Full Binary T r e e

• Parent of node i is node (i/2), unless i = 1


• Node 1 is the root and has no parent

19
Node N u m b e r of Full Binary T r e e

• Left child of node i is node 2i


• where n is the total number of nodes
• If 2i > n, node i has no left child.

20
Node N u m b e r of Full Binary T r e e

• Right child of node i is node 2i+1


• If 2i+1 > n, node i has no right child.

21
Complete B i n a r y Tree with N
Nodes
 Start with a full binary tree that has at least n nodes
 Number the nodes as described earlier
 The binary tree defined by the nodes numbered 1
through n is the n-node complete binary tree
 A full binary tree is a special case of a complete
binary tree

20
Complete B i n a r y Tree

• Complete binary tree with 10 nodes.


• Same node number properties (as in full
binary tree) also hold here.

23
B i n a r y T r e e Representation
• Array representation
• Linked representation

24
A r r a y Representation
• The binary tree is represented in an array by
storing each element at the array position
corresponding to the number assigned to it.
Incomplete B i n a r y Tr ees
Complete binary tree with some missing elements

26
R i g h t - S k e w e d Binary T r e e

• An n node binary tree needs an array whose


length is between n+1 and 2n.
• Right-skewed binary tree wastes the most space
• What about left-skewed binary tree?
• Equally bad, though with trailing blanks that
could be trimmed if known ahead 27
L i n k e d Representation
• The most popular way to present a binary tree
• Each element is represented by a node that has
two link fields (leftChild and rightChild) plus an
item field
• Each binary tree node is represented as an
object whose data type is BinTreeNode
• The space required by an n node binary
tree is n*sizeof(BinTreeNode)

28
L i n ke d Representation

29
Node Class For L i n k e d B i n a r y Tree
class BinTreeNode {
int item;
BinTreeNode *left, *right;

BinTreeNode() {
left = right = NULL;
}
}

30
C o m m o n B i n a r y T r e e Operations
 Determine the height
 Determine the number of nodes
 Make a copy
 Determine if two binary trees are identical
 Display the binary tree
 Delete a tree
 If it is an expression tree, evaluate the expression
 If it is an expression tree, obtain the parenthesized
form of the expression

31
B i n a r y T r e e Traversal

 Many binary tree operations are done by


performing a traversal of the binary tree
 In a traversal, each element of the binary tree is
visited exactly once
 During the visit of an element, all actions (make a
copy, display, evaluate the operator, etc.) with
respect to this element are taken

30
B i n a r y T r e e Traversal M e th o d s
 Preorder
‣ The root of the subtree is processed first before going into the left
then right subtree (root, left, right)
 Inorder
‣ After the complete processing of the left subtree first the root is
processed followed by the processing of the complete right subtree
(left, root, right)
 Postorder
‣ The left and right subtree are completely processed, before the
root is processed (left, right, root)
 Level order
‣ The tree is processed one level at a time
‣ First all nodes in level i are processed from left to right
‣ Then first node of level i+1 is visited, and rest of level i+1 processed

33
Preorder Traversal

void preOrder(BinTreeNode *t) {


if (t != NULL) {
visit(t); // Visit root 1st
preOrder(t->left); // Left Subtree
preOrder(t->right); // Right Subtree
}
}

34
Preorder E xa mp le
(visit action = print)

a b d g h e i c f j

35
Inorder T r a v e rs a l

void inOrder(BinTreeNode *t) {


if (t != NULL) {
inOrder(t->left); // Left Subtree 1st
visit(t); // Visit root
inOrder(t->right); // Right Subtree last
}
}

36
I n o rd e r example

g d h b e i a f j c

36
Inorder by Projection (Squishing)

37
Postorder T r a v e r s a l

void postOrder(BinTreeNode *t) {


if (t != NULL) {
postOrder(t->left); // Left Subtree 1st
postOrder(t->right);// Right Subtree
visit(t); // Visit root last
}
}

39
Postorder E xa m p l e

g h d i e b j f c a

40
Level O r d e r Traversal
void levelOrder(BinTreeNode *t){
Queue<BinTreeNode*> q;
while (t != NULL) {
visit(t); // visit t
// push children to queue
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
t = q.pop(); // next node to visit
}
}
42
Level Order E x a m p l e

 Add and delete nodes from a queue


 Output: a b c d e f g h i j

43
Space a n d T i m e C o m p l e x i t y
• The space complexity of each of the four traversal
algorithms is O(n)
• Why not Ɵ(n)? Size of recursion stack/level queue is
variable.
• The time complexity of each of the four traversal
algorithm is Ɵ(n)
• Each node visited only one

44
Expression Tre e s

44
A r it h m e t ic E x p r e s s io n s

(a + b)*(c + d) + e – f/g*h + 3.25


• Expressions comprise three kinds of entities
 Operators: +, -, /, *
 Operands: a, b, c, d, e, f, g, h, 3.25, (a + b), (c +
d), etc.
 Delimiters (, )
Operator Degree
• Number of operands that the operator
requires
• Binary operator requires two operands
‣ a + b
‣ c / d
‣ e - f
• Unary operator requires one operand
‣ + g
‣ - h
CDS.IISc.ac.in | Department of Computational and DataSciences

Infix F o r m
• Normal way to write an expression.
• Binary operators come in between their left
and right operands.
‣ a * b
‣ a + b * c
‣ a * b / c
‣ (a + b)*(c + d) + e – f/g*h + 3.25
Operator Priorities
• How do you figure out the operands of an
operator?
‣ a + b * c
‣ a * b + c / d
• This is done by assigning operator priorities
‣ B O DM AS: Brackets, Order of powers, Division,
Multiplication, Addition, Subtraction
‣ ( = ) > ^ > * = / > + = -
• When an operand lies between two operators, the
operand associates with the operator with higher
priority
Tie B r e a k e r
• When an operand lies between two
operators with same priority, the operand
associates with the operator on the left
‣ a+b-c  (a+b)-c
‣ a*b/c/d  ((a*b)/c)/d
D e limiters
• Subexpression within brackets/delimiters is treated
as a single operand, independent from the
remainder of the expression
‣ (a + b) * (c – d) / (e – f)
Infix Expression H a r d To Parse
 Need operator priorities, tie breaker, and delimiters
 Makes evaluation by program more difficult
 Postfix and prefix expression forms do not rely on
operator priorities, a tie breaker, or delimiters.
 So it is easier for a computer to evaluate
expressions that are in these forms.
Postfix F o r m
• The postfix form of a variable or constant is
the same as its infix form
‣ a, b, 3.25
• The relative order of operands is the same
in infix and postfix forms.
• Operators come immediately after the
postfix form of their operands.
‣ Infix: a+b
‣ Postfix: ab+
Postfix Exa mp le s
Infix = a + b * c
Postfix = a b c * +

Infix = a * b + c
Postfix = a b * c +

Infix = (a + b) * (c – d) / (e + f)
Postfix = a b + c d - * e f + /

53
U n a r y Operators
 Replace with new symbols
+a  a @
+a + b  a @ b +
-a  a ?
-a - b  a ? b -
Postfix Evaluation
 Scan postfix expression from left to right pushing
operands on to a stack
 When an operator is encountered,
‣ pop as many operands as this operator needs;
‣ evaluate the operator;
‣ push the result on to the stack
 This works because, in postfix, operators come
immediately after their operands
Postfix Evaluation
(a+b)*(c–d)/(e+f)

a b+ c d-* e f+/
a b+ c d-* e f+/
a b+ c d-* e f+/ b
a b+ c d-* e f+/ a
stack
Postfix Evaluation

a b+ c d-* e f+/
a b+ c d-* e f+/
a b+ c d-* e f+/ c-d
a b+ c d-* e f+/ a+b
stack
Postfix Evaluation

a b+ c d-* e f+/
a b+ c d-* e f+/ f
a b+ c d-* e f+/ e
a b+ c d-* e f+/ (a+b)*(c-d)

stack
Postfix Evaluation

a b+ c d-* e f+/
a b+ c d-* e f+/
e+f
(a+b)*(c-d)

stack
Postfix Evaluation

a b+ c d-* e f+/
a b+ c d-* e f+/
(a+b)*(c-
d)/(e+f)

stack
Prefix F o r m
• The prefix form of a variable or constant is the
same as its infix form
‣ a, b, 3.25
• The relative order of operands is the same as in
infix and prefix forms
• Operators come immediately before the
prefix form of their operands.
‣ Infix: a + b
‣ Postfix: ab+
‣ Prefix: +ab
Binary Tree Form
+
a+b
a b

-a -

a
Binary Tree Form
 (a + b) * (c – d) / (e + f)

* +

+ - e f

a b c d
Merits Of B i n a r y T r e e F o r m
 Left and right operands are easy to visualize
 Code optimization algorithms work with the binary
tree form of an expression
 Simple recursive evaluation of expression
/

* +

+ - e f

a b c d
Preorder of Expression Tree
/

* +

+ - e f

a b c d

/ * + a b - c d + e f
Gives prefix form of expression.

34
Inorder of Expression Tree
/

* +

+ - e f

a b c d
a + b * c – d /e + f
• Gives infix form of expression, which is how we
normally write math expressions.
• What about parentheses?
• Fully parenthesized output of the above tree?
38
Postorder of Expression Tree
/

* +

+ - e f

a b c d

a b + c d - * e f + /
Gives postfix form of expression.

41

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy