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

Lecture 8 - Trees

asd

Uploaded by

toprakcihalil0
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)
14 views

Lecture 8 - Trees

asd

Uploaded by

toprakcihalil0
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/ 57

SE 2005

DATA
STRUCTURES
WHAT IS A TREE?
• Tree is a non-linear data structure unlike linked lists, stacks and
queues.

• A tree is a collection of nodes with the following properties:


– The collection can be empty.
– Otherwise, a tree consists of a distinguished node r, called root, and zero or
more nonempty sub-trees T1, T2, … , Tk, each of whose roots are connected by a
directed edge from r.
root

• If a tree is a collection of N
nodes, then it has N-1 edges.

T2
...
T1 Tk
MOTIVATION
• Trees are one of the most
important and extensively
used data structures in
computer science

• Several examples:
– File systems of several
operating systems
– Expression Trees
– Layout of a webpage
Program 1. A simple HTML document.
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>This is a <u>Heading</u></h1>
<p>This is a paragraph with some <u>underlined</u> text.</p>
</body>
</html>

THE TREE
STRUCTURE
OF XML
A rendering of the HTML in Program 1
TREE TERMINOLOGY
Root: The first node from where the tree originates.
The only node in the tree with no parent.

In any tree, there must be only one root node

Edge: The connecting link between any two nodes


In a tree with n number of nodes, there are exactly (n-1)
number of edges
TREE TERMINOLOGY
Parent: The node which has a branch from it to
any other node. In other words, the node which
has one or more children.

Child: The node which is a descendant of some


node.

All the nodes except root node are child nodes


TREE TERMINOLOGY
Siblings: Nodes which belong to the same parent.

Leaf: The node which does not have any child.


Leaf nodes are also called as external nodes or
terminal nodes.

Subtree:

In a tree, each child from a node forms a subtree


recursively.
TREE TERMINOLOGY
Internal Node: The node which has at least one
child

Internal nodes are also called as non-terminal nodes.

The root node is also said to be Internal Node if the


tree has more than one node

Degree: Degree of a node is the total number of


children of that node.

Degree of a tree is the highest degree of a node among


all the nodes in the tree
TREE TERMINOLOGY
Level: each step from top to bottom
The level count starts with 0 and increments by 1 at
each level or step.

Height: Total number of edges that lies on the


longest path from any leaf node to a particular
node

Height of a tree is the height of root node.

Height of all leaf nodes = 0


TREE TERMINOLOGY
Depth: Total number of edges from root node
to a particular node is called as depth of that
node.

Depth of the root node = 0

The terms “level” and “depth” are used


interchangeably.

Path: The sequence of nodes along the edges of


a tree
EXERCISE
• What is the height of this tree?
TYPES OF TREE
• General tree
• Forests
• Binary tree
• Binary search tree
• Adelson-Velskii-
Landis (AVL) tree
• Heap
• B-tree
Binary tree

General
tree

Binary search tree


BINARY
TREE
BINARY TREE
• A binary tree is a special type of tree data structure in which every node can have a
maximum of 2 children.
– branching factor of 2
– branching factor of n is called n-ary

• A binary tree T is a set of nodes with the following properties:


– The set can be empty.
– Otherwise, the set is partitioned into three disjoint subsets:
• a tree consists of a distinguished node r, called root, and
• two possibly empty sets are binary tree, called left and right subtrees of r.

• The binary tree is a useful data structure for rapidly storing sorted data and rapidly
retrieving stored data.
TYPES OF BINARY TREE
• Different types of binary trees are possible. Following are common types of binary
trees:
– Strictly Binary Tree
– Extended Binary Tree
– Complete Binary Tree
– Full Binary Tree
– Skewed Binary Tree
– Binary Expression Tree
– Balanced Binary Tree
– Threaded Binary Tree An ancestry chart which maps to a perfect
– Binary Search Trees depth-4 binary tree
BINARY TREE REPRESENTATIONS
• Binary Trees can be represented in two ways:
– Array Representation
– Linked List Representation
BINARY TREE REPRESENTATIONS
Array Representation of Binary Tree
• One-dimensional array is used to represent a binary tree.
• To represent a binary tree of height ‘h' using array representation, we need one
dimensional array with a maximum size of
• Indexes of other nodes for the ith node, i.e., Arr[i]:
– Arr[(i-1)/2] Returns the parent node
– Arr[(2*i)+1] Returns the left child node
– Arr[(2*i)+2] Returns the right child node

Though it is the simplest technique for memory


representation, it is inefficient as it requires a lot of
memory space.
BINARY TREE REPRESENTATIONS
Linked List Representation of Binary Tree
• We use a doubly linked list to represent a binary tree.
• In a doubly linked list, every node consists of three fields.
– First field for storing left child address,
– second for storing actual data
struct BinaryNode {
– third for storing right child address int data;
struct BinaryNode *left;
struct BinaryNode *right;
};
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node *left;
struct node *right;
};

struct node* newNode(int data) {


struct node* node = (struct node*)malloc(sizeof(struct node)); int main() {
struct node *root = newNode(1);
node->data = data; root->left = newNode(2);
node->left = NULL; root->right = newNode(3);
node->right = NULL; root->left->left = newNode(4);

return(node); return 0;
} }
// Insert on the left of the node
struct node* insertLeft(struct node* root, int
value) {
root->left = createNode(value);
return root->left;
}

// Insert on the right of the node


struct node* insertRight(struct node* root, int
value) { int main() {
root->right = createNode(value); struct node* root = newNode(1);
return root->right;
} insertLeft(root, 12);
insertRight(root, 9);

insertLeft(root->left, 5);
insertRight(root->left, 6);

Return 0
}
TREE TRAVERSAL
• Traversal is a process to visit all the nodes of a tree.

• Because all nodes are connected via edges (links), we always start from the root (head) node.
That is, we cannot randomly access a node in a tree.

• Linear data structures like arrays, stacks, queues, and linked list have only one way to read the
data. But a hierarchical data structure like a tree can be traversed in different ways.
– In-order Traversal
– Pre-order Traversal
– Post-order Traversal

• Generally, we traverse a tree to search or locate a given item or key in the tree or to print all
the values it contains.
IN-ORDER TRAVERSAL
• In this traversal method, the left subtree is
visited first, then the root and later the right
sub-tree. We should always remember that
every node may represent a subtree itself.

• If a binary tree is traversed in-order, the output


will produce sorted key values in an ascending
order.

ALGORITHM
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
D→B→E→A→F→C→G
Step 2 − Visit root node.
Step 3 − Recursively traverse right subtree.
PRE-ORDER TRAVERSAL

• In this traversal method, the root node is visited


first, then the left subtree and finally the right
subtree.

ALGORITHM
Until all nodes are traversed −
Step 1 − Visit root node.
Step 2 − Recursively traverse left subtree. A→B→D→E→C→F→G
Step 3 − Recursively traverse right subtree.
POST-ORDER TRAVERSAL

• In this traversal method, the root node is visited last,


hence the name. First we traverse the left subtree,
then the right subtree and finally the root node.

ALGORITHM
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree. D→E→B→F→G→C→A
Step 2 − Recursively traverse right subtree.
Step 3 − Visit root node.
Inorder

Preorder

Postorder
?
Inorder
10 11 12 13 14 15 17 20 24 26 Postorder
11 13 12 10 17 15 24 26 20 14
Preorder
14 10 12 11 13 20 15 17 26 24
Inorder traversal
5 ->12 ->6 ->1 ->9 ->
Preorder traversal
1 ->12 ->5 ->6 ->9 ->
Postorder traversal
5 ->6 ->12 ->9 ->1 ->
EXAMPLE:

Find n-th node of


inorder traversal
EXAMPLE nth nodes of inorder traversals
struct Node {
int data;
struct Node* left;
struct Node* right;
};

struct Node* newNode(int data) {


struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;

return (node);
}
void NthInorder(struct Node* node, int n){
static int count = 0;
int main()
if (node == NULL)
{
return;
struct Node* root = newNode(10);
root->left = newNode(20);
if (count <= n) {
root->right = newNode(30);
root->left->left = newNode(40);
/* first recur on left child */
root->left->right = newNode(50);
NthInorder(node->left, n);
count++;
int n = 4;
// when count = n then print element
NthInorder(root, n);
if (count == n)
return 0;
printf("%d ", node->data);
}
/* now recur on right child */
NthInorder(node->right, n);
}
}
EXAMPLE
find sum of all the elements

int addBT(Node* root)


{
if (root == NULL)
return 0;
return (root->key + addBT(root->left) + addBT(root->right));
}
BINARY
SEARCH
TREE
BINARY SEARCH TREE
• A Binary search tree (BST) is an ordered binary tree.
• A Binary Search Tree, which is either empty or each
node in the tree contains a key and
– All keys in the left subtree are less than the keys in the
root node,
– All keys in the right subtree are greater than the keys in
the root node,
– The left and right subtrees are also binary search tree.
• Advantages of using binary search tree
– Searching become very efficient
– It also speed up the insertion and deletion operations
as compare to that in array and linked list
EXAMPLE
• Create the binary search tree
using the following data
elements:

43, 10, 79, 90, 12, 54, 11, 9, 50


EXERCİSE
• Create a binary search tree using the following data elements:
– 45, 39, 56, 12, 34, 78, 32, 10, 89, 54, 67, 81
45, 39, 56, 12, 34, 78, 32, 10, 89, 54, 67, 81
OPERATIONS ON BINARY SEARCH
TREE
PREDECESSOR&SUCCESSOR
• Predecessor -> the node
lies behind of given node

• Successor -> the node lies


ahead of given node.
TRAVERSAL
• The tree traversal algorithm
(preorder, postorder and
inorder) are the standard way
of traversing a binary search
tree, which is similar as
traversing in a binary tree.

• In a binary search tree,


inorder traversal always
retrieves data items in
increasing sorted order.
INSERTION
• Allocate the memory for tree.
• Set the data part to the value and
set the left and right pointer of
tree, point to NULL.
• If the item to be inserted, will be
the first element of the tree, then
the left and right of this node will
point to NULL.
• Else, check if the item is less than
the root element of the tree,
– if this is true, then recursively
perform this operation with the
left of the root.
– If this is false, then perform this
operation recursively with the
right sub-tree of the root.
SAMPLE FUNCTIONS

//Find the minimum tree node if //Find the maximum tree node if
available. available.
FindMin(T) FindMax(SearchTree T)
{ {
if(T!=NULL) if(T==NULL)
{ return NULL;
while(T->Left!=NULL) else if(T->Right==NULL)
T=T->Left; return T;
} else
return T; return FindMax(T->Right);
} }
DELETION
• There are three situations of deleting a node from binary search tree.
– The node to be deleted is a leaf node
– The node to be deleted has only one child.
– The node to be deleted has two children.
THE NODE TO BE DELETED IS A LEAF
NODE
• Replace the leaf node with the NULL and simple free the allocated space.
THE NODE TO BE DELETED HAS ONLY
ONE CHILD.
• Replace the node with its child and delete the child node, which now contains the
value which is to be deleted. Simply replace it with the NULL and free the allocated
space
THE NODE TO BE DELETED HAS TWO
CHILDREN.
• The node which is to be deleted, is replaced with its in-order successor or predecessor
recursively until the node value (to be deleted) is placed on the leaf of the tree. After the
procedure, replace the node with NULL and free the allocated space.
SEARCHING

• Compare the element with the root of


the tree.
– If the item is matched then return the
location of the node.
– Otherwise check if item is less than the
element present on root,
• if so then move to the left sub-tree.
• If not, then move to the right sub-tree.
• Repeat this procedure recursively until
match found.
• If element is not found then return
NULL.
struct node* search(int data){
struct node *current = root;

while(current->data != data){

if(current != NULL) {
printf("%d ",current->data);

//go to left tree


if(current->data > data){
current = current->leftChild;
} //else go to right tree
else {
current = current->rightChild;
}

if(current == NULL){//not found


return NULL;
}
}
}

return current;
}
BINARY SEARCH TREE VISUALIZATION

• http://btv.melezinek.c
z/binary-search-
tree.html
TREE APPLICATIONS
• Binary Search Trees(BSTs) are used to quickly check whether an element is present in
a set or not.

• Heap is a kind of tree that is used for heap sort.

• A modified version of a tree called Tries is used in modern routers to store routing
information.

• Most popular databases use B-Trees and T-Trees, which are variants of the tree
structure we learned above to store their data

• Compilers use a syntax tree to validate the syntax of every program you write

You might also like