You are on page 1of 53

Trees

Introduction
 Arrays, linked list ,stacks and queues are
used to represent the linear and tabular data.
 These structure are not suitable for
representing hierarchical data.
 In hierarchical data we have
◦ ancestor, descendant
◦ Superior, subordinate etc.
TREE DEFINED
A tree T is a finite non empty set of elements.
One of these elements is called the root, and
the remaining elements, if any, are portioned
into trees, which are called the sub trees of T.
Introduction to Tree
 Fundamental data storage structures used in
programming.
 Combines advantages of an ordered array

and a linked list.


 Searching as fast as in ordered array.
 Insertion and deletion as fast as in linked list.
Tree (example)

node

g e
e d
Tree Terminology
 Root: node without parent
(A) • Subtree: tree consisting
 Internal node: node with at of a node and its
least one child (A, B, C, F) descendants
 External node (a.k.a. leaf ):
A Level 0
node without children (E, I, J,
K, G, H, D)
 Ancestors of a node: parent,
grandparent etc. B C D
 height of a tree is the
number of edges on the
E F G H
longest simple downward
path from the root to a leaf
 Descendant of a node: child, subtree
I J K
grandchild etc.
 Degree of an element: no. of
children it has
Height of trees??

a) A binary tree on 6 nodes with height 2.


b) A less efficient binary tree with height 4 that contains the same keys.
Tree Terminology
 Path: Traversal from node to node along the edges
results in a sequence called path.
 Root: Node at the top of the tree.
 Parent: Any node, except root has exactly one edge
running upward to another node. The node above it
is called parent.
 Child: Any node may have one or more lines
running downward to other nodes. Nodes below
are children.
 Leaf: A node that has no children.
 Subtree: Any node can be considered to be the root
of a subtree, which consists of its children and its
children’s children and so on.
Binary Trees
 Every node in a binary
tree can have at most
two children.
 The two children of
each node are called
the left child and
right child
corresponding to
their positions.
 A node can have only
a left child or only a
right child or it can
have no children at
all.
Binary Trees
 A binary tree is a tree with the • Applications:
following properties: – arithmetic
◦ Each internal node has at expressions
most two children.
– decision processes
The children of a node are an
ordered pair – searching
 We call the children of an
internal node left child and A
right child
 Alternative recursive
definition: a binary tree is B C
either
◦ a tree consisting of a single
node, or
◦ a tree whose root has an D E F G
ordered pair of children,
each of which is a binary
tree H I
Full and Complete Binary Trees
Full binary tree and Perfect binary
tree
 A full binary tree (sometimes called proper
binary tree or 2-tree or strictly binary tree or
extended binary tree) is a tree in which every
node other than leaves has two children.
 A perfect binary tree is a full binary tree in

which all leaves are at the same depth or


same level
Properties of Full binary Tree

Let T be a nonempty, full binary tree Then:


(a) If T has I internal nodes, the number of leaves
is L = I + 1.
(b) If T has I internal nodes, the total number of
nodes is N = 2I + 1.
(c) If T has a total of N nodes, the number of
internal nodes is I = (N – 1)/2.
(d) If T has a total of N nodes, the number of
leaves is L = (N + 1)/2.
(e) If T has L leaves, the total number of nodes is
N = 2L – 1.
(f) If T has L leaves, the number of internal
nodes is I = L – 1.
Arithmetic Expression Tree
 Binary tree associated with an arithmetic expression
◦ internal nodes: operators
◦ external nodes: operands
 Example: arithmetic expression tree for the
expression (2  (a - 1) + (3  b))

+
 

2 - 3 b

a 1
Compiling arithmetic expressions
 We can represent an arithmetic expression such as
(A + B) * (C + D) * 2 – X / Y
as a binary tree, in which the leaves are constants
or variables and the nodes are operations:


* /
* 2 X Y
+ +

A B C D
Binary Search Trees
 Binary Search Trees:
A binary search tree T is a binary tree that may be
empty. A non empty binary search tree satisfies
the following properties:
1. Every element has a key (or value) and no two
elements have the same key i.e. all keys are
unique.
2. The keys, if any, in the left subtree of the root are
smaller than the key in the node.
3. The keys, if any, in the right subtree of the root
are larger than the key in the node.
4. The left and right sub trees of the root are also
binary search trees.
BST

70 40 70

60 80 10 55 80

30 62 75 92 5 12 75 92

Fig.(a) Fig. (b) Fig. ©

Binary search trees


Representation of Binary & BST
 Array Representation
 Linked list representation
Array Representation
 In this representation the binary tree is
represented by storing each element at the
array position corresponding to the number
assigned to each number (nodes)
 In this representation, a binary tree of height

h requires an array of size (2h+1-1), in the


worst case
Array Representation
 For simplicity , consider the array is
indexed with an index set beginning from
1 not 0.

1 2 3 4 5 6 7
70 60 80 30 62 75 92

Array representation of BST in fig (a)


1 2 3 4 5 6 7
40 10 55 5 12

Array representation of BST in fig (b)


1 2 3 4 5 6 7
70 80 75 92

Array representation of BST in fig (c)


BST
70

72

80

85
Fig. (d)

1 2 3 4 5 6 7 8 9 10 11 12 1314 15
70 72 80 85
Disadvantages of array
representation
 This scheme of representation leads to
wastage of space when binary tree is skewed
or number of elements are small as compared
to its height.
 Array representation is useful only when the

binary tree is perfect or complete.


Linked representation
 The most popular and practical way of representing a
binary tree is using links (pointers).

70

60 80

X 30 X X 62 X X 75 X X 92 X

Linked representation of binary search tree of figure (a)


Linked representation

40

10 X 55 X

X 5 X X 12 X

Linked representation of binary search tree of figure (b)


Linked representation

X 70

80

X 75 X X 92 X

Linked representation of binary search tree of figure (c)


Linked representation

X 70

X 72

X 80

X 85 X
Linked Representation
 In linked representation, each element is
represented by a node that has exactly two link
fields.
 Field names are left and right.
 Each node has data field called info.

The node structure is defined as:


struct nodetype
{
struct nodetype *left;
int info;
struct nodetype *right;
};
BST Insertion
 Change the dynamic Tree-Insert(T,
Tree-Insert(T,z)z)
set represented by a 1. yy
1. NIL NIL
BST. 2. xx
2. root[T]
root[T]
 Ensure the binary- 3. whilexxNIL
3. while NIL
search-tree property
holds after change.
4.
4. doyy
do xx
 Insertion is easier than 5.
5. ififkey[z]
key[z]<<key[x]
key[x]
deletion. 6.
6. thenxx
then left[x]
left[x]
7.
7. elsexx
else right[x]
right[x]
8. p[z]
8. p[z] yy
9.
9. ififyy==NILNIL
10.
10. then root[t]
thenroot[t] zz
11.
11. else
elseififkey[z]
key[z]<<key[y]
key[y]
12.
12. then left[y]
then left[y] zz
13.
13. else right[y]
elseright[y] zz
Department of CSE 28
BST Insertion-Analysis
 Initialization: O(1) Tree-Insert(T,
Tree-Insert(T,z)z)
1. yy
1. NIL NIL
 While loop in lines 3-7 2. xx
2. root[T]
root[T]
searches for place to 3. whilexxNIL
3. while NIL
insert z, maintaining
parent y.
4.
4. doyy
do xx
5.
5. ififkey[z]
key[z]<<key[x]
key[x]
This takes O(h) time.
6.
6. thenxx
then left[x]
left[x]
 Lines 8-13 insert the 7.
7. elsexx
else right[x]
right[x]
value: O(1) 8. p[z]
8. p[z] yy
9.
9. ififyy==NILNIL
 TOTAL: O(h) time to 10.
10. then root[t]
thenroot[t] zz
insert a node. 11.
11. else
elseififkey[z]
key[z]<<key[y]
key[y]
12.
12. then left[y]
then left[y] zz
13.
13. else right[y]
elseright[y] zz
Department of CSE 29
Example
 Given a sequence of numbers:
11, 6, 8, 19, 4, 10, 5, 17, 43, 49, 31
 Draw a binary search tree by inserting the

above numbers from left to right.


Searching in BST
 Here k is the key that is searched for and x is
the start node.
 BST-Search(x, k)

1: y ← x
2: while y != nil do
3: if key[y] == k then return y
4: else if key[y] < k then y ← right[y]
5: else y ← left[y]
6: return (“NOT FOUND”)
Example
Traversing a Binary Tree
 Preorder (NLR Traversal)
◦ Process the root R.
◦ Traverse the left subtree of R in preorder.
◦ Traverse the right subtree of R in preorder.
 Inorder (LNR Traversal)
◦ Traverse the left subtree of R in inorder.
◦ Process the root R.
◦ Traverse the right subtree of R in inorder.
Traversing a Binary Tree(contd..)
 Postorder (LRN Traversal)
◦ Traverse the left subtree of R in postorder.
◦ Traverse the right subtree of R in postorder.
◦ Process the root R.

Department of CSE 34
Preorder, Postorder and Inorder
Traversal Example
 PreOrder - 8, 5, 9, 7, 1,
12, 2, 4, 11, 3

 InOrder - 9, 5, 1, 7, 2,
12, 8, 4, 3, 11

 PostOrder - 9, 1, 2, 12,
7, 5, 3, 11, 4, 8

 LevelOrder - 8, 5, 4, 9,
7, 11, 1, 12, 3, 2
36
BST Inorder Traversal
56

26 200

18 28 190 213

12 24 27

Sorted Order:
12,18,24,26,27,28,56,190,200,213
37
Example
 Pre-order: A B D E G H C F
 In order: D B G E H A C F

 Draw the binary tree T.


Example

Pre- Order: A B D E G H C F

Roo Left subtree LTA Right subtree RTA


t

In- Order: B D G E H A C F

Left subtree LTA Roo Right subtree RTA


t
Example:
Partial Tree

RTA
LTA

D B C F
G E H

Pre- Order: B D E G H

In- Order: D B G E H
Example

Pre- Order: B D E G H

Roo Left subtree LTB Right subtree RTB


t

In- Order: D B G E H

Left subtree LTB Roo Right subtree RTB


t
Example:
Partial Tree

B
RTA

C F
D
G RTB
E H

Pre- Order: E G H

In- Order: G E H
Example

Pre- Order: E G H

Roo Left subtree LTE Right subtree RTE


t

In- Order: G E H

Left subtree LTE Roo Right subtree RTE


t
Example:
Partial Tree

B
RTA

C F
D E

G H

Pre- Order: C F

In- Order: C F
Example

Pre- Order: C F

Roo Left subtree LTC Right subtree RTC


t

In- Order: C F

Left subtree LTC Roo Right subtree RTC


t
Example:

B
C

D E F

G H
Algo for Pre-order Traversal
Finding Min & Max
The binary-search-tree property guarantees that:
» The minimum is located at the left-most node.
» The maximum is located at the right-most node.

Tree-Minimum(xx))
Tree-Minimum( Tree-Maximum(xx))
Tree-Maximum(
1. while left
1. while left[[xx]]  NIL
NIL 1. while right
1. while right[[xx]]  NIL
NIL
2.
2. do do xx  left
left[[xx]] 2. do xx 
2. do  right
right[[xx]]
3. return xx
3. return 3. return xx
3. return
Successor
 Successor of node x is the node y such that
key[y] is the smallest key greater than key[x].
 The successor of the largest key is NIL.
 Search consists of two cases.

◦ If node x has a non-empty right subtree, then x’s


successor is the minimum in the right subtree of x.
◦ If node x has an empty right subtree, then:
 As long as we move to the left up the tree (move up through
right children), we are visiting smaller keys.
 x’s successor y is the node that x is the predecessor of (x is
the maximum in y’s left subtree).
 In other words, x’s successor y, is the lowest ancestor of x
whose left child is also an ancestor of x.
Pseudo-code for Successor
Tree-Successor(xx))
Tree-Successor(
 ifif right
right[[xx]]  NIL
NIL
2.
2. then
then return Tree-Minimum(right
return Tree-Minimum( right[[xx])])
3.
3. yy   pp[[xx]]
4. while yy  NIL
4. while and xx =
NIL and = right
right[[yy]]
5.
5. do xx 
do  yy
6.
6. yy  pp[[yy]]
7. return yy
7. return
56

26 200
Code for predecessor is symmetric.

18 28 190 213
Running time: O(h)

12 24 27
Deletion in BST
 The overall strategy for deleting a node z from a binary
search tree T has three basic cases:

1. If z has no children, then we simply remove it by


modifying its parent to replace z with NIL as its child.
2. If z has just one child, then we elevate that child to take
z’s position in the tree by modifying z’s parent to replace z
by z’s child.
3. If z has two children, then we find z’s successor y—
which must be in z’s right subtree—and have y take z’s
position in the tree.
Deletion Algorithm

You might also like