0% found this document useful (0 votes)
82 views

Lec7 PDF

Tree data structures are hierarchical and non-linear. They consist of nodes connected by parent-child relationships, with a single root node at the top. Binary trees restrict nodes to having at most two children. Binary trees can be traversed in preorder, inorder, and postorder manners. Binary search trees (BSTs) organize nodes to efficiently search for values, with all left descendants less than the root and all right descendants greater than the root.

Uploaded by

Sohaib
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

Lec7 PDF

Tree data structures are hierarchical and non-linear. They consist of nodes connected by parent-child relationships, with a single root node at the top. Binary trees restrict nodes to having at most two children. Binary trees can be traversed in preorder, inorder, and postorder manners. Binary search trees (BSTs) organize nodes to efficiently search for values, with all left descendants less than the root and all right descendants greater than the root.

Uploaded by

Sohaib
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Tree

Introduction to trees
• Sofar we have discussed mainly linear data structures – strings, arrays,
lists, stacks and queues

• Now we will discuss a non-linear data structure called tree.

• Trees are mainly used to represent data containing a hierarchical


relationship between elements, for example, records, family trees and
table of contents.

• Consider a parent-child relationship


Ashim Lamichhane 2
Ashim Lamichhane 3
Tree

• Atree is an abstract model of a hierarchical structure that consists of


nodes with a parent-child relationship.

• Tree is a sequence of nodes

• There is a starting node known as a root node

• Every node other than the root has a parentnode.


• Nodes may have any number of children

Ashim Lamichhane 4
Ashim Lamichhane 5
Ashim Lamichhane 6
Some Key Terms:
• Root − Node at the top of the treeis called root.

• Parent − Any node except root node has one edge upward to a node called parent.

• Child − Node below a given node connected by its edge downward is called its child node.

• Sibling – Child of same node are called siblings

• Leaf − Node which does not have any child node is called leaf node.

• Sub tree − Sub tree represents descendants of a node.

• Levels − Level of a node represents the generation of a node. If root node is at level 0, then itsnext child node
is at level 1, its grandchild is at level 2 and soon.

• keys − Key represents a value of a node based on which a search operation is to be carried out for anode.

Ashim Lamichhane 7
Some Key Terms:
• Degree of a node:
• The degree of a node is the number of children of that node
• Degree of a Tree:
• The degree of a tree is the maximum degree of nodes in a giventree
• Path:
• It is the sequence of consecutive edges from source node to destination node.
• Height of a node:
• The height of a node is the max path length form that node to a leaf node.
• Height of a tree:
• The height of a tree is the height ofthe root
• Depth of atree:
• Depth of a tree is the max level of any leaf in the tree

Ashim Lamichhane 8
Ashim Lamichhane 9
Characteristics of trees
• Non-linear data structure
• Combines advantages of an ordered array
• Searching as fast as in ordered array
• Insertion and deletion as fast as in linked list
• Simple and fast

Ashim Lamichhane 10
Application
• Directory structure of a file store
• Structure of an arithmetic expressions
• Used in almost every 3D video game to determine what objects need to be
rendered.
• Used in almost every high-bandwidth router for storingrouter-tables.
• used in compression algorithms, such as those used by the .jpeg and .mp3 file-
formats.

Ashim Lamichhane 11
Introduction ToBinary Trees
• Abinary tree, is a tree in which no node can have more than two
children.

• Consider a binary tree T,here ‘A’ is the root node of the binary tree T.

• ‘B’ is the left child of ‘A’ and ‘C’ is theright


child of ‘A’
• i.e Ais a father of BandC.
• The node B and Care called siblings.

• Nodes D,H,I,F,J are leafnode


Ashim Lamichhane 12
Binary Trees
• Abinary tree, T, is either empty or suchthat
I. T has a special node called the root node
II. T has two sets of nodes LTand RT, called the left subtree and right subtree of
T, respectively.
III. LTand RT are binary trees.

Ashim Lamichhane 13
Binary Tree
• Abinary tree is a finite set of elements that are either empty or is
partitioned into three disjointsubsets.

• The first subset contains a single element called the root of the tree.

• The other two subsets are themselves binary trees called the left and right
sub-trees of the originaltree.

• Aleft or right sub-tree can beempty.

• Each element of a binary tree is called a node of the tree.

Ashim Lamichhane 14
The following figure shows a binary tree with 9 nodes where A is the root

Ashim Lamichhane 15
Binary Tree
• The root node of this binary tree isA.

• The left sub tree of the root node, which we denoted by LA, is theset
LA= {B,D,E,G} and the right sub tree of the root node, RAis the set
RA={C,F,H}

• The root node of LAis node B, the root node of RAis Cand so on

Ashim Lamichhane 16
Binary TreeProperties
• If a binary tree contains m nodes at level L, it contains atmost 2m
nodes at level L+1

• Since a binary tree can contain at most 1 node at level 0 (the root), it
contains at most 2L nodes at level L.

Ashim Lamichhane 17
Types of BinaryTree
• Complete binary tree
• Strictly binary tree
• Almost complete binary tree

Ashim Lamichhane 18
Strictly binary tree
• If every non-leaf node in a binary tree has nonempty leftand right sub-trees, then
such a tree is called a strictly binary tree.

• Or, to put it another way, all of the nodes in a strictly binary tree are of degree zero
or two, never degreeone.

• Astrictly binary tree with


N leaves always contains 2N – 1 nodes.

Ashim Lamichhane 19
Complete binary tree
• Acomplete binary tree is a binary tree in which every level, except possibly the last, is completely
filled, and all nodes are as far left as possible.

• Acomplete binary tree of depth d is called strictly binary tree if all of whose leaves are at level d.

• Acomplete binary tree has 2d nodes at every depthd and 2d -1 non leaf nodes

Ashim Lamichhane 20
Almost complete binary tree
• An almost complete binary tree is a tree where for a right child, thereis always a
left child, but for a left child there may not be a right child.

Ashim Lamichhane 21
Ashim Lamichhane 22
Ashim Lamichhane 23
Treetraversal
• Traversal is a process to visit all the nodes of a tree and may print their
values too.

• All nodes are connected via edges (links) we always start from theroot
(head) node.

• There are three ways which we use to traverse atree


• In-order Traversal
• Pre-order Traversal
• Post-order Traversal

• Generally we traverse a tree to search or locate given item or key in the tree
or to print all the values it contains.

Ashim Lamichhane 24
Pre-order, In-order, Post-order
• Pre-order
<root><left><right>

• In-order
<left><root><right>

• Post-order
<left><right><root>

Ashim Lamichhane 25
Pre-order Traversal
• The preorder traversal of a nonempty binary tree is defined asfollows:
• Visit the root node
• Traverse the left sub-tree in preorder
• Traverse the right sub-tree in preorder

Ashim Lamichhane 27
Pre-order Pseudocode
struct Node{
char data;
Node *left;
Node *right;
}
void Preorder(Node *root)
{
if (root==NULL) return;
printf (“%c”, root->data);
Preorder(root->left);
Preorder(root->right);
}

Ashim Lamichhane 27
In-order traversal
• The in-order traversal of a nonempty binary tree is defined asfollows:
• Traverse the left sub-tree in in-order
• Visit the root node
• Traverse the right sub-tree in inorder

• The in-order traversal output


of the given tree is
H D I BEA FCG

Ashim Lamichhane 28
In-order Pseudocode
struct Node{
char data;
Node *left;
Node *right;
}
void Inorder(Node *root)
{
if (root==NULL) return;
Inorder(root->left);
printf (“%c”, root->data);
Inorder(root->right);
}

Ashim Lamichhane 29
Post-order traversal
• The in-order traversal of a nonempty binary tree is defined asfollows:
• Traverse the left sub-tree in post-order
• Traverse the right sub-tree in post-order
• Visit the root node

• The in-order traversal output


of the given tree is
H I D EBFGCA

Ashim Lamichhane 30
Post-order Pseudocode
struct Node{
char data;
Node *left;
Node *right;
}
void Postorder(Node *root)
{
if (root==NULL) return;
Postorder(root->left);
Postorder(root->right);
printf (“%c”, root->data);
}

Ashim Lamichhane 31
Binary SearchTree(BST)

• A binary search tree (BST) is a binary tree that is either empty or in


which every node contains a key (value) and satisfies the following
conditions:
• All keys in the left sub-tree of the root are smaller than the key in the root
node
• All keys in the right sub-tree of the root are greater than the key in the root
node

• The left and right sub-trees of the root are again binary search trees

Ashim Lamichhane 32
Binary SearchTree(BST)

Ashim Lamichhane 33
Binary SearchTree(BST)
• Abinary search tree is basically a binary tree, and therefore it can be
traversed in inorder, preorder and postorder.

• If we traverse a binary search tree in inorder and print the identifiers


contained in the nodes of the tree, we get a sorted list of identifiers in
ascending order.

Ashim Lamichhane 34
Why Binary SearchTree?
• Let us consider a problem of searching a list.

• If a list is ordered searching becomes faster if we use contiguous


list(array).

• But if we need to make changes in the list, such as inserting new


entries or deleting old entries, (SLOWER!!!!) because insertion and
deletion in a contiguous list requires moving many of the entries every
time.

Ashim Lamichhane 35
Why Binary SearchTree?
• So we may think of using a linked list because it permits insertion
and deletion to be carried outby adjusting only few pointers.

• But in an n-linked list, there is no way to move through thelist other


than one node at a time, permitting only sequentialaccess.

• Binary trees provide an excellent solution to this problem. By making


the entries of an ordered list into the nodes of a binary search tree, we
find that we can search for a key in O(logn)

Ashim Lamichhane 36
Binary SearchTree(BST)

Time Complexity
Array Linked List BST
Search O(n) O(n) O(logn)
Insert O(1) O(1) O(logn)
Remove O(n) O(n) O(logn)

Ashim Lamichhane 37
Operations on Binary Search Tree(BST)
• Following operations can be done in BST:

• Search(k, T): Search for key k in the tree T.If k is found in some node of tree
then return true otherwise returnfalse.

• Insert(k, T): Insert a new node with value k in the info field in the tree Tsuch
that the property of BSTis maintained.

• Delete(k, T):Delete a node with value k in the info field from the tree Tsuch
that the property of BSTis maintained.

• FindMin(T), FindMax(T): Find minimum and maximum element from the


given nonempty BST.
Ashim Lamichhane 38
Searching Through TheBST
• Compare the target value with the element in the root node
✓ If the target value is equal, thesearch is successful.
✓If target value is less, search the leftsubtree.
✓If target value is greater, search the rightsubtree.
✓If the subtree is empty, thesearch is unsuccessful.

Ashim Lamichhane 39
Ashim Lamichhane 40
Insertion of a node inBST
• Toinsert a new item in a tree, we must first verify that itskey is different
from those of existingelements.

• If a new value is less, than the current node's value, go to the left subtree,
else go to the right subtree.

• Following this simple rule, the algorithm reaches a node, which has noleft
or right subtree.

• By the moment a place for insertion is found, we can say for sure, thata
new value has no duplicate in the tree.

Ashim Lamichhane 41
Algorithm for insertion in BST
• Check, whether value in current node and a new value are equal. If so,
duplicate is found. Otherwise,

• if a new value is less, than the node's value:


• if a current node has no leftchild, place for insertion has been found;
• otherwise, handle the left child with the same algorithm.

• if a new value is greater, than the node's value:


• if a current node has no right child, place forinsertion has been found;
• otherwise, handle the right child with the same algorithm.

Ashim Lamichhane 42
Ashim Lamichhane 43
Ashim Lamichhane 44
Deleting a node from theBST
• While deleting a node from BST,there may be three cases:
1. The node to be deleted may be a leaf node:
• In this case simply delete a node and set null pointer to itsparents those side
at which this deleted nodeexist.

Ashim Lamichhane 45
Deleting a node from theBST
2. The node to be deleted has one child
• In this case the child of the node to be deleted is appended to its parent node.
Suppose node to be deleted is 18

Ashim Lamichhane 46
Deleting a node from theBST

Ashim Lamichhane 47
Ashim Lamichhane 48
Ashim Lamichhane 49
Splay Trees

● In balanced tree schemes, explicit rules are


followed to ensure balance.
● In splay trees, there are no such rules.
● Search, insert, and delete operations are like in
binary search trees, except at the end of each
operation a special step called splaying is done.
● Splaying ensures that all operations take O(lg n)
amortized time.
● First, a quick review of BST operations…
Splaying

● In splay trees, after performing an ordinary


BST Search, Insert, or Delete, a splay
operation is performed on some node x (as
described later).
● The splay operation moves x to the root of the
tree.
● The splay operation consists of sub-operations
called zig-zig, zig-zag, and zig.
Zig-Zig

z x has a grandparent x
10 30
y y
20 20
x z
T1 30 10 T4

T2 T3

T3 T4 T1 T2

(Symmetric case too)

Note: x’s depth decreases by two.


Zig-Zag

z x has a grandparent x
10 20
y
30
x z y
T1 20 10 30
T4

T2 T3 T1 T2 T3 T4

(Symmetric case too)

Note: x’s depth decreases by two.


Zig
x has no grandparent (so, y is the root)
y Note: w could be NIL x
10 20
x
20
w y w
T1 30 10 30

T2

T3 T4 T1 T2 T3 T4

(Symmetric case too)

Note: x’s depth decreases by one.


Top Down Splay Trees

● Works by starting at the top and working down to produce a


similar result.
● All of the nodes lower than the target are put into one tree and
all of the nodes greater than the target are put into another tree
then it is recombined.
Top Down Splaying
Top Down Splaying
Top Down Splaying
Complete Example

44

Splay(78) 50

17 88

32 65 97
zig-zag
28 54 82

z
29 76
y
80
x 78
Complete Example

44

Splay(78) 50

17 88

32 65 97
zig-zag
28 54 82

x
29 78

z 76 80 y
Complete Example

44

Splay(78) 50

17 88

32 z 65 97
zig-zag
y
28 54 82

29 78 x

76 80
Complete Example

44

Splay(78) 50

17 88

32 x 78 97
zig-zag
28 z 65 y 82

29 54 76 80
Complete Example

44
z
Splay(78) 50

17 88 y

32 x 78 97
zig-zag
28 65 82

29 54 76 80
Complete Example

44
x
Splay(78) 78

17 50 z 88 y

82
32 97
zig-zag 65
80
28
54 76

29
Complete Example

y 44
x
Splay(78) 78

17 50 88 w

82
32 97
zig 65
80
28
54 76

29
Complete Example
78 x
y 44

Splay(78)
17 50 88 w

82
32 97
zig 65
80
28
54 76

29
AVL Tree is…

● Named after Adelson-Velskii and Landis


● the first dynamically balanced trees to be
propose
● Binary search tree with balance condition in
which the sub-trees of each node can differ by
at most 1 in their height
Definition of a balanced tree

● Ensure the depth = O(log N)


● Take O(log N) time for searching, insertion,
and deletion
● Every node must have left & right sub-trees of
the same height
An AVL tree has the following
properties:

1. Sub-trees of each
node can differ by
at most 1 in their
height
2. Every sub-trees is
an AVL tree
AVL tree?

YES NO
Each left sub-tree has Left sub-tree has height 3,
height 1 greater than each but right sub-tree has height
right sub-tree 1
AVL tree

Height of a node
● The height of a leaf is 1. The height of a null
pointer is zero.
● The height of an internal node is the maximum
height of its children plus 1

Note that this definition of height is different from the one we


defined previously (we defined the height of a leaf as zero
previously).
AVL Trees
10 10

5 20 5 20

3 3 43

1
2

1 3
AVL Trees

12

8 16

4 10 14

2 6
AVL Tree

-1 0

0 0 -1 1

0 0 0 0
AVL Tree -2 AVL Tree

1 0

0 -1

0 Not an AVL Tree


INTRODUCTI
ON
 A B+ tree is a balanced tree in which every path from the
root of the tree to a leaf is of the same length, and each
non leaf node of the tree has between [n/2] and [n]
children, where n is fixed for a particular tree.

 In a B+ tree, in contrast to a B-tree, all records are stored


at the leaf level of the tree; only keys are stored in internal
nodes.

 All the leaf nodes are interconnected for faster access.

 Fill factor is 50%.


EXAMPL
EB+ Trees use a "fill factor" to control the growth and the

shrinkage. A 50% fill factor would be the minimum forany
B+.

Example : A B+ tree of order 5.

 Number of Keys 4
 Number of Pointers 5

 Fill Factor 50%

 Minimum Keys in each node 2

You might also like