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

Data Structures: Trees

Department of CSE

1
Sofar we discussed Linear data structures like
Linked list

A B C \0

Head

stack
• Data is represented in single level (Linear fashion).
2
Trees Basics
• Data will be represented in multiple
levels
• Now we will discuss a non-linear data
structure called tree.
• Each level contains a single data or
collection of data (Linear data
structures).
• 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
3
Natural View of a Tree

leaves

branches
root

4
Computer Scientist’s View

root

leaves

branches

5
Trees

Binary Tree Binary Search


Trees

• Insertion
• Traversing
• Search
• Deletion

6
Trees Basics

Tree:
A tree 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 parent node.
• Nodes may have any number of children

7
Tree Terminology
1. Root-node without parent (A)
2. Siblings-nodes share the same parent.
3. Leaf-node: nodes without children (G,
H, I,J,E).
4. Internal node-node with at least one
child (A, B, C, D,F).
5. Ancestors of a node: parent,
grandparent, grandgrandparent, etc.
6. Descendant of a node: child,
grandchild, grand-grandchild, etc.
7. Subtree: tree consisting of a node and
its descendants

8
9
Tree Terminology

10
The depth of a node in a binary tree is the length of
the path from the root of the tree to that node. That is,
the root has depth 0, its children have depth 1, its
grandchildren have depth 2 11
A Tree Representation

• A node is represented by an
data type storing 
• Element
• Parent node B
• Sequence of children nodes
 

A D F
B

A D F

 
C E
C E
Introduction ToBinary Trees
• A binary 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 the


right child of ‘A’
• i.e A is a father of B andC.
• The node B and Care called siblings.

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

13
Introduction ToBinary Trees
• A binary 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 ofT, respectively.
III. LTand RT are binary trees.

14
Represent Binary TreesinC

15
Traversal Binary Trees

• 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 the root (head)
node.
• There are three ways which we use to traverse a tree
• 1.Pre-order Traversal (root, left, right)
2. In-order Traversal (left, root, right)
3. Post-order Traversal (left, right, root)
• Generally we traverse a tree to search or locate given item or value in the tree
or to print all the values it contains.

16
Traversal Binary Trees

Pre-order, In-order, Post-order


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

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

• Post-order
<left><right><root>
17
Pre-Order Traversal Binary Trees
• The pre-order 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

18
Pre-Order Traversal Binary Trees

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);
} 19
In-Order Traversal Binary Trees
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 outp of the


given tree is
H D I BEA FCG

20
In-Order Traversal Binary Trees
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);
}
21
Post-Order Traversal Binary Trees

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

• The post-order traversal


outp of the given tree is
H I D EBFGCA

22
Post-Order Traversal Binary Trees

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);
} 23
Arithmetic Expression Using BT

inorder traversal
+
A/B*C*D+E
infix expression
* E
preorder traversal

* D +**/ABCDE
prefix expression
/ C postorder traversal
AB/C*D*E+
A B postfix expression

24
Basics of Binary Search Trees
Binary Search Tree(BST)
• A binary search tree (BST) is a binary tree that is either empty or in which every
node contains a value and satisfies the following conditions:
• All values in the left sub-tree of the root are smaller than the value in the root node
• All values in the right sub-tree of the root are greater than the value in the root node

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

25
Binary Search Trees

26
Why Binary Search Trees?
• 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.
• Sowe may think of using a linked list because it permits insertion and deletion to
be carried outby adjusting only few pointers.
• 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 value in O(logn)

27
Binary Search Trees
• 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.
Time Complexity
Array Linked List BST
Search O(n) O(n) O(logn)
Remove O(n) O(n) O(logn)

28
Operations on Binary Search Trees
• 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.

29
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 left
subtree.
✓If target value is greater, search the
rightsubtree.
✓If the subtree is empty, thesearch is
unsuccessful.

30
Insertion of a node in BST

• 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.

31
Algorithm for Insertion of a node 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.

32
33
34
Deleting a node in BST
• 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.

35
Deleting a node in BST
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 is18

36
Deleting a node in BST

37
Algorithm for Deleting a node in BST

38
39
Applications of Trees
• Binary tree for an arithmetic expression
• internal nodes: operators
• leaves: operands
• Example: arithmetic expression tree for the expression
((2  (5 - 1)) + (3  2))

 

2 - 3 2

5 1

40
Trees Application

1. Directory structure of a file store


2. Structure of an arithmetic expressions
3. Used in almost every 3D video game to determine what objects need to be
rendered.
4. Used in almost every high-bandwidth router for storing router-tables.
5. used in compression algorithms, such as those used by the .jpeg and .mp3 file
formats.

41
C Program for different Traversals of Binary Tree
#include <stdio.h> struct node* createNode(int value)
#include <stdlib.h> {
struct node { struct node* newNode = malloc(sizeof(struct node));
int data; newNode->data = value;
struct node* left; newNode->left = NULL;
struct node* right; newNode->right = NULL;
};
return newNode;
void inorder(struct node* root){ }
if(root == NULL) return;
void main()
inorder(root->left);
{
printf("%d ->", root->data);
struct node* root = createNode(1);
inorder(root->right);
root->left=createNode(12);
}
root->right=createNode(9);
void preorder(struct node* root){
root->left->left=createNode(10);
if(root == NULL) return;
root->left->right=createNode(15);
printf("%d ->", root->data);
preorder(root->left);
printf("Inorder traversal \n");
preorder(root->right);
inorder(root);
}
printf("\nPreorder traversal \n");
void postorder(struct node* root) {
preorder(root);
if(root == NULL) return;
postorder(root->left);
printf("\nPostorder traversal \n");
postorder(root->right);
postorder(root);
printf("%d ->", root->data); 42
}
}
C Program for Creating Binary Search Tree
#include <stdio.h>
#include <stdlib.h> void inorder(struct node* root){
struct node { if(root == NULL) return;
int data; inorder(root->left);
struct node* left; printf("%d ->", root->data);
struct node* right; inorder(root->right);
}; }
struct node *newNode(int item) void main()
{ {
struct node *temp = (struct node *)malloc(sizeof(struct node)); struct node *root = NULL;
temp->data = item; root = insert(root, 50);
temp->left = temp->right = NULL;
return temp;
insert(root, 30);
} insert(root, 20);
insert(root, 40);
struct node* insert(struct node *node, int value)
{
insert(root, 70);
if (node == NULL) return newNode(value); insert(root, 60);
if (value < node->data) insert(root, 80);
node->left = insert(node->left, value); printf("\ninorder traversal \n");
else if (value > node->data) inorder(root);
node->right = insert(node->right, value);
return node; } 43
}

You might also like