Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views86 pages

Module3 Tree

Uploaded by

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

Module3 Tree

Uploaded by

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

Module 3

Tree

© Oxford University Press 2014. All rights


Non-Linear Data Structure - Trees
Datastructure to represent data containing hierarchical
relationship between data elements,
Eg. Family Tree (Parent – Child Relationship!!)
, Table of Contents etc.

© Oxford University Press 2014. All rights


© Oxford University Press 2014. All rights
Trees
• A tree is a structure which is mainly used to store data that is hierarchical in
nature.
• A tree is recursively defined as a set of one or more nodes where one node is
designated as the root of the tree and all the remaining nodes can be
partitioned into non-empty sets each of which is a sub-tree of the root.

• Node A is the root node;


• Nodes B, C, and D are
children of the root node
and form sub-trees of the
tree rooted at node A

© Oxford University Press 2014. All rights


Basic Terminology
• Root node
– The root node R is the topmost node in the tree.
– If R = NULL, then it means the tree is empty

• Sub-trees
– If the root node R is not NULL, then the
– trees T1 , T2 , and T3 are called the sub-trees of R.

• Leaf node
– A node that has no children is called the leaf node or the
terminal node
© Oxford University Press 2014. All rights
Basic Terminology
• Path
– A sequence of consecutive edges is called a path.
– the path from the root node A to node I is given as:
• A, D, and I
• Ancestor Node
– any predecessor node on the path from root to that node
– root node does not have any ancestors
– nodes A, C, and G are the ancestors of node K

• Descendent node
– any successor node on any path from the node to a leaf node
– Leaf nodes do not have any descendants.
– nodes C, G, J, and K are the descendants of node A

© Oxford University Press 2014. All rights


Basic Terminology
• Level number
– Every node in the tree is assigned a level number.
– root node is at level 0 ; children of the root node are at level no 1
– every node is at one level higher than its parent
– all child nodes have a level no given by parent’s level no + 1 .

• Degree of a Node
– = number of children that a node has
– The degree of a leaf node is zero

• In degree
– In-degree of a node is the number of edges arriving at that node

• Out degree
– Out-degree of a node is the number of edges leaving that node

© Oxford University Press 2014. All rights


General Trees
• General trees are data structures that store elements hierarchically.
• The top node of a tree is the root node and each node, except the root, has a parent.
• A node in a general tree (except the leaf nodes) may have zero or more sub-trees.
• General trees which have 3 sub-trees per node are called ternary trees.
• However, the number of sub-trees for any node may be variable. For example, a node
can have 1 sub-tree, whereas some other node can have 3 sub-trees.

© Oxford University Press 2014. All rights


General Tree

Even the algorithms for searching, traversing, adding, and deleting nodes
become much more complex as there are not just two possibilities for any
node but multiple possibilities.
© Oxford University Press 2014. All rights
Binary Trees
• A binary tree is a data structure which is defined as a collection of
elements called nodes.
• In a binary tree, the topmost element is called the root node, and each
node has 0, 1, or at the most 2 children.
• Every node contains a data element, a "left" pointer which points to the
left child, and a "right" pointer which points to the right child.
• The root element is pointed by a "root" pointer.
• If root = NULL, then it means the tree is empty.

1 ROOT NODE

T1 T2
2 3

R – Root node (node 1)


4
5 6 7
T1- left sub-tree (nodes 2, 4, 5, 8, 9)
T2- right sub-tree (nodes 3, 6, 7, 10, 11, 12)
1 1 1
8 9 0 1 2

© Oxford University Press 2014. All rights


Binary Trees - Key Terms
• Parent: If N is any node in T that has left successor S1 and right successor
S2, then N is called the parent of S1 and S2. Correspondingly, S1 and S2 are
called the left child and the right child of N. Every node other than the root
node has a parent.
• Sibling: S1 and S2 are said to be siblings. In other words, all nodes that are
at the same level and share the same parent are called siblings (brothers).
• Level number: Every node in the binary tree is assigned a level number.
The root node is defined to be at level 0. The left and right child of the root
node have a level number 1. Similarly, every node is at one level higher
than its parents.
• Leaf node: A node that has no children. (or Terminal Node)
• Degree: Degree of a node is equal to the number of children that a node
has.

© Oxford University Press 2014. All rights


© Oxford University Press 2014. All rights
Binary Trees - Key Terms
• Depth: The depth of a node N is given as the length of the path from
the root to the node N. The depth of the root node is zero.
• Height:
Height
• It is the total number of nodes on the path from the root node to the
deepest node in the tree.
• A tree with only a root node has a height of 1.
• A binary tree of height h has at least h nodes and at most 2h – 1 nodes.
• This is because every level will have at least one node and can have at
most 2 nodes.
• The height of a binary tree with n nodes is at least log2(n+1)

© Oxford University Press 2014. All rights


Binary Trees - Key Terms
• Similar binary trees: Given two binary trees T and T’ are said to be similar if both these trees
have the same structure.
TREE T
TREE T”
A F

B C G H

D I

E J

• Copies of binary trees: Two binary trees T and T’ are said to be copies if they
have similar structure and same content at the corresponding nodes.
TREE T
TREE T”
A A

B C B C

E
D E D

© Oxford University Press 2014. All rights


Binary Tree
• A tree in which every node can have a
maximum of two children is called as Binary
Tree.
Full Binary Tree
• A binary tree in which every node has either
two or zero number of children is called Full
Binary Tree
Complete Binary Trees
• A complete binary tree is a binary tree which satisfies two properties.
• First, in a complete binary tree every level, except possibly the last, is completely filled.
• Second, all nodes appear as far left as possible
• In a complete binary tree Tn, there are exactly n nodes and level r of T can have at most 2 r nodes.
• The formula to find the parent, left child and right child can be given as:
• If K is a parent node, then its left child can be calculated as
2 * K and its right child can be calculated as 2 * K + 1.
For example, the children of node 4 are 8 (2*4) and 9 (2* 4 + 1).
• Similarly, the parent of node K can be calculated as | K/2 |.

2 3

4 7
5 6

Ex : tree T13 has exactly 13 nodes 8 9 1


0
1
1
1
2
1
3

© Oxford University Press 2014. All rights


• The formula to find the parent, left child and right child can be given as:
• If K is a parent node, then its left child can be calculated as
2 * K and its right child can be calculated as 2 * K + 1.
For example, the children of node 4 are 8 (2*4) and 9 (2* 4 + 1).
• Similarly, the©
parent of University
Oxford node K canPress
be calculated
2014. Allas | K/2 |.
rights
Tree Terminology
• Root: node without parent (A)
• Leaf : node without children (E,I,..) • Degree of a tree: the
• Siblings: nodes share the same maximum number of its node.
parent • Subtree: tree consisting of a
• Internal node: node with at least node and its descendants
one child (A, B, C, F)
• External node (leaf ): node
without children (E, I, J, K, G, H, D) A
• Ancestors of a node: parent,
grandparent, grand-grandparent,
etc.
• Descendant of a node: child, B C D
grandchild, grand-grandchild, etc.
• Depth of a node: number of
ancestors E F G H
• Height of a tree: maximum depth
of any node
• Degree of a node: the number of
its children I J K
Binary Tree Representation
1. Sequential representation using arrays
2. List representation using Linked list
Linked Representation of Binary Trees
• In computer’s memory, a binary tree can be maintained either using a linked representation or using
sequential representation.
• In linked representation of binary tree, every node will have three parts: the data element, a pointer to
the left node and a pointer to the right node. So in C, the binary tree is built with a node type given as
below.
struct node
{
struct node* left;
int data;
1
struct node* right;
}; 2 3

4 5 6 7

X 8 X X 9 X X 10 X X 11 X X 12 X

Empty sub-trees are represented using X


(meaning NULL).

© Oxford University Press 2014. All rights


List representation
struct node
{
int data;
struct node *left;
struct node *right;
}
Given the memory representation of a tree that stores the names of family members,
construct the corresponding tree from the given data
Sequential representation of binary trees
• The root of the tree will be stored in the
first location.

• That is, TREE[1] will store the data of the


root element.

• The children of a node stored in location K


will be stored in locations (2 × K) and
(2 × K+1).

• The maximum size of the array TREE is


given as (2h –1), where h is the height of the
tree.

• An empty tree or sub-tree is specified using


NULL. If TREE[1] = NULL, then the tree is
empty
Sequential representation
• Advantages:
– Direct access to all nodes (Random access)
• Disadvantages:
– Height of tree should be known
– Memory may be wasted
– Insertion and deletion of a node is difficult
List representation
• Advantages:
– Height of tree need not be known
– No memory wastage
– Insertion and deletion of a node is done without
affecting other nodes
• Disadvantages:
– Direct access to node is difficult
– Additional memory required for storing address of
left and right node
List representation
struct node
{
int data;
struct node *left;
struct node *right;
}
Traversing a Binary Tree
• Traversing a binary tree is the process of visiting each node in
the tree exactly once in a systematic way.

• Unlike linear data structures in which the elements are


traversed sequentially, tree is a nonlinear data structure in
which the elements can be traversed in many different ways.

• There are different algorithms for tree traversals.


– Preorder Traversal
– In order Traversal
– Postorder Traversal
Pre-order Traversal Algorithm
• To traverse a non-empty binary tree in pre-
order, the following operations are performed
recursively at each node.
node
• The algorithm works by:
1.Visiting the root node,
2.Traversing the left sub-tree, and finally
3.Traversing the right sub-tree.
Pre-order Traversal - Recursive Algorithm

1. void Preorder (struct node *tree) {


2. if(tree == NULL) return ;
3. printf(“%d”, tree->data);
4. Preorder(tree->left);
Preorder
5. Preorder(tree-right);
Preorder
6. }
Pre-order Traversal Algorithm
• The pre-order traversal of the tree is given as
A, B, C
– Root node first, the left sub-tree next,
and then the right sub-tree
• Also called as depth-first traversal
– The left sub-tree is always traversed before the right
sub-tree
– ‘pre’ in the pre-order specifies that the root node is
accessed prior to any other nodes in the left and right
sub-tree
– also known as the NLR traversal algorithm
(Node-Left-Right).
Find the sequence of nodes that will be visited
using pre-order traversal algorithm.
Find the sequence of nodes that will be visited
using pre-order traversal algorithm.
Find the sequence of nodes that will be visited
using pre-order traversal algorithm.
Find the sequence of nodes that will be visited
using pre-order traversal algorithm.
In-order Traversal Algorithm
• To traverse a non-empty binary tree in pre-
order, the following operations are performed
recursively at each node.
node
• The algorithm works by:
1.Traversing the left sub-tree
2.Visiting the root node, and finally
3.Traversing the right sub-tree.
In-order Traversal - Recursive Algorithm

1. void Inorder (struct node *tree) {


2. if(tree == NULL) return ;
3. Inorder(tree->left);
Inorder
4. printf(“%d”, tree->data);
5. Inorder(tree-right);
Inorder
6. }
in-order Traversal Algorithm
• The in-order traversal of the tree is given as
B, A, C
– Left sub-tree first, the root node next,
– and then the right sub-tree
• Also called as Symmetric traversal
– The left sub-tree is always traversed before the root
node and the right sub-tree
– ‘in’ in the in-order specifies root node is accessed in
between the left and the right sub-trees.
– also known as the LNR traversal algorithm
– (Left-Node-Right).
Find the sequence of nodes that will be visited
using in-order traversal algorithm.
Find the sequence of nodes that will be visited
using in-order traversal algorithm.
Find the sequence of nodes that will be visited
using in-order traversal algorithm.
Find the sequence of nodes that will be visited
using in-order traversal algorithm.
Post-order Traversal Algorithm
• To traverse a non-empty binary tree in pre-
order, the following operations are performed
recursively at each node.
node
• The algorithm works by:
1.Traversing the left sub-tree
2.Traversing the right sub-tree. , and finally
3.Visiting the root node
Post-order Traversal - Recursive Algorithm

1. void Postorder (struct node *tree) {


2. if(tree == NULL) return ;
3. Postorder(tree->left);
Postorder
4. Postorder(tree-right);
Postorder
5. printf(“%d”, tree->data);
6. }
Post-order Traversal Algorithm
• The post-order traversal of the tree is given as
B, C, A
– Left sub-tree first, the right sub-tree next,
– and then the root node

– The left sub-tree is always traversed before the right


sub-tree and root node and
– the ‘post-order’ specifies that the root node is
accessed after the left and the right sub-trees.
– LRN traversal algorithm (Left-Right-Node).
Find the sequence of nodes that will be visited
using post-order traversal algorithm.
Find the sequence of nodes that will be visited
using post-order traversal algorithm.
Find the sequence of nodes that will be visited
using post-order traversal algorithm.
Find the sequence of nodes that will be visited
using post-order traversal algorithm.
Level order traversal
• In level-order traversal, all the nodes at a level are accessed
before going to the next level.
• This algorithm is also called as the breadth-first traversal
algorithm.

© Oxford University Press 2014. All rights


Expression Trees
• Binary trees are widely used to store algebraic expressions. For
example, consider the algebraic expression Exp given as:
Exp = (a – b ) + ( c * d)
• This expression can be represented using a binary tree as shown
in figure

- *

a b c d

© Oxford University Press 2014. All rights


Binary Expression Trees
• Construct Binary Expression Tree from infix expression
• Exp = (a – b ) + ( c * d)

• Rule :
• 1. operand stored in leaf node ; operator – internal node
• 2. root – minimum precedence operator (evaluated at last), leaf –
highest precedence operator goes bottom
Expression Trees
• Binary trees are widely used to store algebraic expressions. For
example, consider the algebraic expression Exp given as:
Exp = (a – b ) + ( c * d)
• This expression can be represented using a binary tree as shown
in figure

- *

a b c d
• Expression Tree?
Prefix notation?

© Oxford University Press 2014. All rights


Prefix notation?

© Oxford University Press 2014. All rights


Prefix notation?

© Oxford University Press 2014. All rights


Prefix notation?

© Oxford University Press 2014. All rights


Efficient Binary Trees

© Oxford University Press 2014. All rights


Binary Search Tree (BST)
• Binary Search Tree constraint
• Properties
• Create a BST
• Searching for a node in BST
• Inserting a new node in a BST
• Delete a node from BST
Binary Search Trees
• A binary search tree (BST), also known as an ordered binary
tree, is a variant of binary tree in which the nodes are arranged
in order.
• In a BST, all nodes in the left sub-tree have a value less than
that of the root node.
• Correspondingly, all nodes in the right sub-tree have a value
either equal to or greater than the root node.
• The same rule is applicable to every sub-tree in the tree.

© Oxford University Press 2014. All rights


Binary Search Tree

39

27 45

18
29 40 54

9 21 28 36 59

10 19 65

60

• Recursively each of the sub-trees obeys the BST constraint


© Oxford University Press 2014. All rights
BST Properties
• BST is a binary tree with the following
properties:
1. The left sub-tree of a node N contains values that
are less than N’s value.
2. The right sub-tree of a node N contains values
that are greater than N’s value.
3. Both the left and the right binary trees also satisfy
these properties and, thus, are binary search
trees
BST Efficient!
• Nodes in a BST are ordered, the time needed to
search an element in the tree is greatly reduced
– Do not traverse the entire tree
– At every node, we get a hint regarding which sub-tree to
search in
• Average running time of a search operation is
– O(log2 n)
– as at every step, we eliminate half of the sub-tree from the
search process.
BST Efficient!
• Due to its efficiency in searching elements,
– BST are widely used in dictionary problems where the
code always inserts and searches the elements that are
indexed by some key value

• In worst case, a BST will take


O(n) time to search for an
element.
• The worst case would occur
when the tree is a linear chain
of nodes
a) b) c)
Creating a Binary Search from Given Values
45, 39, 56, 12, 34, 78, 32, 10, 89, 54, 67

© Oxford University Press 2014. All rights


Creating a Binary Search from Given Values
45, 39, 56, 12, 34, 78, 32, 10, 89, 54, 67
45

45
45
45 45 45 45 39 56

39 56
39 56
39 39 56 39 56 12 78

12 78
12
12 34

34
45 34
32

39 56 45
45

12 78 39 56
39 56

10 34 12 54 78
12 54 78

10 34 89
32
10 34 67 89

32
32

© Oxford University Press 2014. All rights


Searching for a Value in a BST
• The search function is used to find whether a given value is present in the tree or not.
• The function first checks if the BST is empty. If it is, then the value we are searching for is
not present in the tree, and the search algorithm terminates by displaying an appropriate
message.
• However, if there are nodes in the tree then the search function checks to see if the key
value of the current node is equal to the value to be searched.
• If not, it checks if the value to be searched for is less than the value of the node, in which
case it should be recursively called on the left child node.
• In case the value is greater than the value of the node, it should be recursively called on the
right child node.

© Oxford University Press 2014. All rights


© Oxford University Press 2014. All rights
© Oxford University Press 2014. All rights
Algorithm to Search a Value in a BST

searchElement (TREE, VAL)


Step 1: IF TREE->DATA = VAL OR TREE = NULL, then
Return TREE
ELSE
IF VAL < TREE->DATA
Return searchElement(TREE->LEFT, VAL)
ELSE
Return searchElement(TREE->RIGHT, VAL)
[END OF IF]
[END OF IF]

Step 2: End

© Oxford University Press 2014. All rights


© Oxford University Press 2014. All rights
Inserting a new node in BST

The insert function is used to add a new node with a given value at the correct position in the binary search tree.

Adding the node at the correct position means that the new node should not violate the properties of the binary search tree.

© Oxford University Press 2014. All rights


© Oxford University Press 2014. All rights
Algorithm to Insert a Value in a BST

Insert (TREE, VAL)

Step 1: IF TREE = NULL, then


Allocate memory for TREE
SET TREE->DATA = VAL
SET TREE->LEFT = TREE ->RIGHT = NULL
ELSE
IF VAL < TREE->DATA
Insert(TREE->LEFT, VAL)
ELSE
Insert(TREE->RIGHT, VAL)
[END OF IF]
[END OF IF]

Step 2: End

© Oxford University Press 2014. All rights


Deleting a Value from a BST
• The delete function deletes a node from the binary search tree.
• However, care should be taken that the properties of the BSTs do
not get violated and nodes are not lost in the process.
• The deletion of a node involves any of the three cases.

© Oxford University Press 2014. All rights


Deleting a Value from a BST
• The delete function deletes a node from the binary search tree.
• However, care should be taken that the properties of the BSTs do not get violated and nodes are
not lost in the process.
• The deletion of a node involves any of the three cases.
Case 1: Deleting a node that has no children.
children
For example, deleting node 78 in the tree below.

45 45 45 45

39 56 39 56 39 56 39 56

54 78 54 78 54 78 54

55 55 55 55

© Oxford University Press 2014. All rights


Deleting a Value from a BST
• Case 2: Deleting a node with one child (either left or right).
• To handle the deletion, the node’s child is set to be the child of the node’s parent.
• Now, if the node was the left child of its parent, the node’s child becomes the left child of the node’s
parent.
• Correspondingly, if the node was the right child of its parent, the node’s child becomes the right child of the
node’s parent.

© Oxford University Press 2014. All rights


Deleting a Value from a BST
• Case 2: Deleting a node with one child (either left or right).
• To handle the deletion, the node’s child is set to be the child of the node’s parent.
• Now, if the node was the left child of its parent, the node’s child becomes the left child of the node’s
parent.
• Correspondingly, if the node was the right child of its parent, the node’s child becomes the right child of the
node’s parent.

45 45 45 45

39 56 39 56 39 56 39 56

54 78 54 78 54 78 55 78

55 55 55

© Oxford University Press 2014. All rights


Deleting a Value from a BST
• Case 3: Deleting a node with two children.
• To handle this case of deletion, replace the node’s value with its
in-order predecessor (largest value in the left sub-tree) or in-
order successor (smallest value in the right sub-tree).

© Oxford University Press 2014. All rights


Deleting a Value from a BST
• Case 3: Deleting a node with two children.
• To handle this case of deletion, replace the node’s value with its
in-order predecessor (largest value in the left sub-tree) or in-
order successor (smallest value in the right sub-tree).
• The in-order predecessor or the successor can then be deleted
using any of the above cases.
45 45 45 45

39 56 39 56 39 55 39 55

54 78 54 78 54 78 54 78

55 80 55 80 55 80 80

© Oxford University Press 2014. All rights


Deleting a Value from a BST

• Case 3: Deleting a node with two children.


– in-order successor (smallest value in the right sub-
tree).

© Oxford University Press 2014. All rights


Construction of BST when only
preorder or post-order is given
• Preorder : 20, 16, 5, 18, 17, 19, 60, 85, 70

• Note : Inorder ofUniversity


© Oxford BST isPress
always inrights
2014. All sorted order
Construction of BST when only given
postorder
• Postorder : 5, 17, 19, 18, 16, 70, 85, 60, 20

• Note : Inorder ofUniversity


© Oxford BST isPress
always inrights
2014. All sorted order

You might also like