Dsa L8 PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

CS F211: DATA STRUCTURES & ALGORITHMS Chittaranjan Hota, PhD

Professor of Computer Sc.


GENERAL TREE, BINARY TREE ADT BITS-Pilani Hyderabad Campus
hota[AT]hyderabad.bits-pilani.ac.in
NATURE LOVER VS. DSA PROGRAMMER’S VIEW OF A
TREE
leaves
leaves root

branches branches

root nodes

(Image source: Sartaj Sahani’s DSA lecture)


TREES: NON-LINEAR DATA STRUCTURES
•In computer science, a tree is an abstract data type
(ADT) that stores elements in a hierarchical structure.
•A tree consists of nodes with a parent-child relation.
Each element has a parent and zero or more children
elements (except the root).
•Applications:
• Computer File systems.
• Finding a pattern, fast search/insert/delete etc. (A Tree representing organizational structure
• Indexing in databases, Syntax tree in compilers. of Company xyz)
• Shortest path trees in Routers
Formally, we define tree T to be a set of nodes storing elements in a parent-child relationship with the
following properties:
- If T is nonempty, it has a special node, called the root of T, that has no parent.
- Each node v of T different from the root has a unique parent node w; every node with parent w
is a child of w.
TREE TERMINOLOGIES AND PROSPERITIES
Root: node without parent (A)
Internal node: node with at least one child (A, A
B, C, F)
External node (a.k.a. leaf ): node without
children (E, I, J, K, G, H, D) B C D

Ancestors of a node: parent, grandparent,


grand-grandparent, etc. E F G H
Depth of a node: number of ancestors
Height of a tree: maximum depth of any node
I J K
(3) subtree
Descendant of a node: child, grandchild,
grand-grandchild, etc.
CONTINUED… 3
President What is the degree of this tree?
Tree degree = Max node degree

2 VP1 1 VP2 1 VP3

0 Manager1 Manager2 0 Manager3 1 Manager4 0

Worker1 0
ORDERED TREES
•A tree is ordered if
there is a linear
ordering defined for
the children of each
node; that is, we can
identify children of a If T1 and T2 are
node as being the first,
ordered trees then
second, third, and so
on. T1 ≠ T2 else T1 = T2.

•Ordered trees
typically indicate the
linear order What
relationship existing (An ordered tree associated with a book) about
between siblings. this?
WHAT ABOUT THESE?
TREE ADT
We use Positions to abstract nodes as • Query methods:
Nodes are internal aspects of our • boolean p.isRoot()
Implementation. The operator * is
used as a dereferencing operator to • boolean p.isExternal()
access a node. • Additional update methods may be defined by data
•Generic methods: structures implementing the Tree ADT.
 integer size()
 boolean empty()
•Accessor methods:
 position root()
 list<position> positions()
•Position-based methods: (An informal interface (An informal interface for the tree ADT)
 position p.parent() for a position in a tree)
 list<position> p.children()
A LINKED STRUCTURE FOR GENERAL TRESS

NULL

(The node structure) (The portion of the data structure associated (Running times of the functions of
with root node and its children) an n-node linked tree structure)
TREE TRAVERSAL ALGORITHMS
The height of a node p in a tree T is also defined recursively:
Algorithm depth(T, p):
-If p is external, then the height of p is 0.
if p.isRoot() then -Otherwise, the height of p is one plus the
maximum height of a child of p
return 0
else Algorithm height1(T): Algorithm height2(T, p):
h=0 if p.isExternal() then
return 1 + depth(T, p.parent()) for each p ∈ T.positions() do return 0
if p.isExternal() then else
The running time of algorithm depth(T, p) is h = max(h,depth(T, p)) h=0
O(dp), where dp denotes the depth of the return h for each q ∈ p.children()
(The height of a tree is equal to
node p in the tree T. the maximum depth of its external
do h=max(h,height2(T,q))
nodes) return 1+h
Worst case complexity is O(n) where there
height2 spends O(1+cp) time at
are ‘n’ nodes in the tree. O(n2)
each node p O(n)
PREORDER TRAVERSAL
•A traversal of a tree T is a systematic way of
accessing, or “visiting,” all the nodes of T.
•In a preorder traversal, a node is visited
before its descendants.
•Application: print a structured document

1
Make Money Fast!
Algorithm preOrder(v) {
visit(v); 2 5 9
for each child w of v 1. Motivations 2. Methods References
preorder (w); 3 4
6 7 8
} 1.1 Greed 1.2 Avidity
2.1 Stock 2.2 Ponzi 2.3 Bank
Fraud Scheme Robbery
POSTORDER TRAVERSAL
•In a postorder traversal, a node is visited after
its descendants.
•Application: compute space used by files in a
directory and its subdirectories.
9
csf211/
Algorithm postOrder(v){
8
for each child w of v 3 7
notices.txt
postOrder (w); homeworks/ programs/
1K
visit(v);
1 2 4 5 6
}
h1.doc h2.doc p1.cpp p2.cpp p3.cpp
2K 5K 7K 22K 18K
BINARY TREES
•A binary tree is a tree with the following properties:
 Each internal node has at most two children (exactly two for
proper binary trees)
(A Full Binary tree (Proper): All nodes have
 The children of a node are an ordered pair
either 0 or two children. Both types of nodes
•We call the children of an internal node left child and right can appear at all the levels in the tree)
child
•Alternative recursive definition: a binary tree is either
 a tree consisting of a single node, or
 a tree whose root has an ordered pair of children, each of which
is a binary tree
• Applications:
• arithmetic expression evaluations
• decision processes (A Complete binary tree: At the lowest level the
• Routing table in a router nodes have zero children, and at the level
• Search trees above that nodes can have 0, 1 or 2 children)
EXAMPLE USAGES
Binary tree associated with an arithmetic expression Binary tree associated with a decision process:
 internal nodes: operators - internal nodes: questions with yes/no
 external nodes: operands answer
- external nodes: decisions
Example: arithmetic expression tree for the
Example: Breakfast decision
expression (2  (a - 4) + (5  b))

+ Want a quick breakfast?


Yes No
 
Coffee & burger? Pizza and Pasta
2 - 5 b
Yes No Yes No
@CafeCoffeeDay Inst Cafe Bits&bytes Alankrita
a 4
PROPERTIES OF A PROPER BINARY TREE
Notation
N: number of nodes, e: number of external nodes, i: number of internal nodes, and h: height

• Properties:
• e=i+1
• n = 2e - 1
• hi
• h  (n - 1)/2
• e  2h
• h  log2 e
• h  log2 (n + 1) - 1
BINARY TREE ADT
•The BinaryTree ADT extends the Tree ADT, i.e., it inherits all the methods of the
Tree ADT
Additional methods:
 position p.left()
 position p.right()

• Update methods may be defined by data structures implementing the


BinaryTree ADT
• Proper binary tree: Each node has either 0 or 2 children
INORDER TRAVERSAL
•In an inorder traversal a node is visited after its left subtree and before its right subtree
Application: draw a binary tree
 x(v) = inorder rank of v
 y(v) = depth of v 6

Algorithm inOrder(v) 8
if  v.isExternal() 2
inOrder(v.left()) 4 9
7
visit(v) 1
if  v.isExternal()
3 5
inOrder(v.right())
PRINT ARITHMETIC EXPRESSION
Specialization of an inorder traversal Algorithm printExpression(v)
 print operand or operator when visiting node if v.isExternal()
 print “(“ before traversing left subtree print(“(’’)
 print “)“ after traversing right subtree inOrder(v.left())
print(v.element())
+ if v.isExternal()
inOrder(v.right())
  print (“)’’)

2 - 5 b

a 4 ((2  (a - 4)) + (5  b))


EVALUATE ARITHMETIC EXPRESSION
Specialization of a postorder traversal
 recursive method returning the value of a subtree
 when visiting an internal node, combine the values of the subtrees

+ Algorithm evalExpr(v)
if v.isExternal()
  return v.element()
else
x  evalExpr(v.left())
2 - 3 2
y  evalExpr(v.right())
  operator stored at v
5 1 return x  y
EULER TOUR TRAVERSAL Eulerian
graph:
Source
•Generic traversal of a binary tree (Wiki)
•We can unify the tree-traversal algorithms (in-order, pre-order, and post-order) into a single framework
by relaxing the requirement that each node be visited exactly once.
•Walk around the tree and visit each node three times:
 on the left (preorder)
 from below (inorder)
 on the right (postorder) +
+: It allows for more  
L R
general kinds of algorithms
B
to be expressed easily. -
2 3 2
Applications: printing fully
parenthesized expression, 5 1
finding no. of descendants
etc. https://www.geeksforgeeks.org/
IMPLEMENTATION OF TREES: LINKED STRUCT.
A node is represented by an object storing B 
 Element
 Parent node
 Sequence of children nodes
A  D F 
Node objects implement the Position ADT

A D F
C  E 
C E
LINKED STRUCTURE FOR BINARY TREES

 root
B 5
size

 
A D
B

A D
   
C E
C E
BINARY TREE IMPLEMENTATION USING LINKED
STRUCT

7 8
Complete code @ http://csis.bits-hyderabad.in/csf211

3 4
BINARY TREE UPDATE FUNCTIONS

expandExternal(const Position& p)
removeAboveExternal (const Position& p)
A VECTOR-BASED IMPLEMENTATION OF BINARY
TREE
• A simple structure for representing a binary tree T is based on a way of numbering the nodes
of T.
• If v is the root of T, then f(v) = 1; If v is the left child of node u, then f(v) = 2f(u); If v is the right
child of node u, then f(v) = 2f(u) +1  function f is called level numbering function.

(General scheme) (An Example Expression tree)


CONTINUED…

The vector implementation of a binary tree is a fast


and easy way of realizing the binary-tree ADT, but
it can be very space inefficient if the height of the
tree is large.  O(2n), where ‘n’ is no. of nodes in T.
(Example binary tree using a vector)
BINARY SEARCH TREES

More later

(Searching successfully 36 through blue solid path, and unsuccessfully 71 through dashed path)
THE TEMPLATE FUNCTION PATTERN
•The template function pattern describes a generic computation method that can be
tuned for a particular application by redefining certain steps.

(Member function eulerTour recursively traverses


(Class EulerTour defining a generic Euler tour
the tree and accumulates the results)
of a binary tree. It realizes template function
pattern and must be specialized for use)
CONTINUED…

(Implementation of class EvaluateExpressionTour


which specializes EulerTour to evaluate the expression (A derived class, called PrintExpressionTour that prints the
associated with an arithmetic expression tree) arithmetic expression)
THANK YOU!
Next Class: Priority Queue ADT …

You might also like