You are on page 1of 62

TREE

Binary and Binary search Tree


Non-Linear Data Structure

• The data structures that we have discussed in previous lectures are


linear data structures.
• The arrays, linked list, queue and stack are linear data structures.
• There are a number of applications where linear data structures are
not appropriate. In such cases, there is need of some non-linear
data structure.
• Tree is one of the non-linear data structures.
Tree
• This figure is showing a genealogy tree of a family.

Muhammad Aslam Khan

T
.
Sohail Aslam Javed Aslam Yasmeen Aslam

Haaris Saad Qasim Asim Fahd Ahmed Sara Omer


Trees
• A tree is a collection of nodes
• The collection can be empty (called the null tree or empty tree)
• (recursive definition) If not empty, a tree consists of a distinguished node
r (the root), and zero or more nonempty sub trees T1, T2, ...., Tk, each of
whose roots are connected by a directed edge from r
Binary Trees
A tree in which no node can have more than two children

The mathematical definition of a binary tree is



“A binary tree is a finite set of elements that is either empty or is partitioned into three disjoint subsets. The
first subset contains a single element called the root of the tree. The other two subsets are themselves binary
Left the
trees called sub-tree
left and right sub-trees”. Each element of a binary tree is called a nodeRight
of thesub-tree
tree.
Binary Tree
Root
A

Left successor B C Right successor

D E F

G H I

•The node A, B, C and F have two successors, the node E have


only one successor, and the node D,G,H, and I have no
successor.

•The left sub-tree of root A consists of the nodes B,D,E, and G, and
the right sub-tree of A consists of the node C,F,H, and I.
A non-tree Structure
A

B C

D E F

G H I

• In this figure we join the node G with D. Now this is not a tree. It is due to
the reason that in a tree there is always one path to go (from root) to a
node. But in this figure, there are two paths (tracks) to go to node G.
A non-tree Structure
A

B C

D E F

H I
G
A

B C

F
D E

H I
G
Strictly Binary Tree

• There is a version of the binary tree, called strictly binary tree.


• A binary tree is said to be a strictly binary tree if every non-leaf node in a binary tree
has non-empty left and right sub-trees.
A

B C

D E J F

G K H I

• Now all the non-leaf nodes (A, B, C, E and F) have their left and right children so
according to the definition, it is a strictly binary tree.
Some Terminologies
Father/Parent A

B C

D E F
Leaves/Terminal
Child/Son
G H I

Child and parent


Siblings/Brothers
Every node except the root has one parent 
A node can have an arbitrary number of children
Leaves/Terminal
Nodes with no children
Sibling/Brothers
Nodes with same parent
Some Terminologies
 Edge
 The line drawn from node N to T is called the edge
 Path
 Sequence of consecutive edges is called the path.
 Branch
 Path ending on a leaf is called branch.
 Length
 number of edges on the path
 Ancestor and Descendant
 Node L is called a (right or left) descendant of node N, and N is called an
ancestor of L
Some Terminologies
 Depth or Height of a node
 Length of the longest path from that node to a leaf
 The height of a node v is the maximum number of edges in a path from v to a
descendant of v.
 The depth of a node v is the number of edges in the path from the root to v
 The depth of a tree is equal to the depth of the deepest leaf
 The depth of the tree is?

 Level
 The level of a node in a binary tree is defined as follows:
 Root has level 0,
 Level of any other node is one more than the level of its parent (father).
Level of nodes of a tree

A 0 ----------------------------------------Level 0

B 1 C 1 ------------------- Level 1

D E 2 F 2 ------- Level 2

H 3 I 3-----Level 3
G 3
Complete Binary Tree

• Now, if there are left and right sub-trees for each node in the binary tree, it
becomes a complete binary tree.
• The definition of the complete binary tree is

“A complete binary tree of depth d is the strictly binary tree all of whose
leaves are at level d”.
A

B C

D E F G

H I J K L M N O
Complete Binary Tree

We know that the property of the binary tree is


that its node can have a maximum of two sub-
trees, called as left and right sub-trees.
The nodes increase at each level, as the tree
grows downward.
In a complete binary tree, the nodes increase in a
particular order.
 Node at level 0 is 1, which is equal to 2 0
 Nodes at level 1 is 2, which is equal to 2 1
 Nodes at level 2 is 4, which is equal to 2 2.
 Nodes at level 3 is 8, which is equal to 2 3.
Nodes at each Level

A ------------- Level 0: 20 nodes

B ----- Level 1: 21 nodes ------ C

E Level 2: 22 nodes
F ------------- G
D -------------

H I M N O
J K L

------------------------ Level 3: 23 nodes ------------------------------


Number of Nodes, Leaf Nodes and Non-
Leaf Nodes

 The total number of nodes in a complete binary tree of depth d will be 2d+1 –
1.
 If there is a complete binary tree of depth 4, the total number of nodes in it
will be?
24+1 - 1 = 25 – 1 = 32 – 1 = 31
  Thus the total number of nodes in the complete binary tree of depth 4 is 31.
  In a complete binary tree, all the leaf nodes are at the depth level d. So the
number of nodes at level d will be 2d . These are the leaf nodes.
 Thus the difference of total number of nodes and number of leaf nodes will
give us the number of non-leaf (inner) nodes. It will be (2 d+1 – 1) – 2d i.e. 2d –
1.
 Thus we conclude that in a complete binary tree, there are 2d leaf nodes and
2d – 1 non-leaf (inner) nodes.
Level of a Complete Binary Tree
• We can find the depth of a complete binary tree if we know the total
number of nodes.
• If we have a complete binary tree with n total nodes, then by the equation
of the total number of nodes we can write
• Total number of nodes = 2d+1 – 1 = n
• To find the value of d, we solve the above equation as under

2d+1 – 1 = n
2d+1 = n + 1
d + 1 = log2 (n + 1)
d = log2 (n + 1) – 1

• After having n total nodes, we can find the depth d of the tree by the above
equation. Suppose we have 100,000 nodes. It means that the value of n is
100,000, reflecting a depth i.e. d of the tree will be log2 (100000 + 1) – 1,
which evaluates to 20. So the depth of the tree will be 20. In other words,
the tree will be 20 levels deep.
Example: Expression Trees

• Leaves are operands (constants or variables)


• The other nodes (internal nodes) contain operators
Question
• Draw the diagram of tree.

• (a + b*c)+((d*e + f )*g)
• (5* ( 6 + 2)) – 12/4
• (2x+y)(5a-b)3
• (A* B-C)- ((D/E ^ F) * G)
Representing Binary Tree in
Memory
• Linked representation of binary tree
• Root: Contains the location of the root R of the tree
• Info: Contains the data at the node.
• Left: Contains the location of the left child of the node
• Right: Contains the location of the right child of the node

• Sequential representation of binary tree


Tree traversal- Depth-First Traversal
• Used to print out the data in a tree in a certain order
• Pre-order traversal
– Process the root R.
– Travers the left sub-tree of R
– Travers the right sub-tree of R
• In-order traversal
– Travers the left sub-tree of R
– Process the root R.
– Travers the right sub-tree of R
• Post-order traversal
– Travers the left sub-tree of R
– Travers the right sub-tree of R
– Process the root R.
Preorder, Postorder and Inorder

• Pre-order traversal
• node, left, right
• prefix expression
• ++a*bc*+*defg

• In-order traversal
• left, node, right.
• infix expression
• a+b*c+d*e+f*g

• Post-order traversal
• left, right, node
• postfix expression
• abc*+de*f+g*+
Breadth-First Traversal
• The breadth-first traversal of a tree visits the nodes in the order of their
depth in the tree. Breadth-first traversal first visits all the nodes at depth
zero (i.e., the root), then all the nodes at depth one, and so on. At each
depth the nodes are visited from left to right.

• A breadth-first traversal of the tree shown in Figure  visits the nodes in the
following order:
• A,B,D,C,E,H,F,G,I
Question
• Derive Pre-order, Post-order and In-order expression
Algorithm
void preorder(TreeNode<int>* treeNode)
{
if( treeNode != NULL )
{
cout << *(treeNode->getInfo())<<" ";
preorder(treeNode->getLeft());
preorder(treeNode->getRight());
}
}

void inorder(TreeNode<int>* treeNode) void postorder(TreeNode<int>* treeNode)


{ {
if( treeNode != NULL ) if( treeNode != NULL )
{ {
inorder(treeNode->getLeft()); postorder(treeNode->getLeft());
cout << *(treeNode->getInfo())<<" "; postorder(treeNode->getRight());
inorder(treeNode->getRight()); cout << *(treeNode->getInfo())<<" ";
} }
} }
preorder(14)
Preorder Recursion 14
14
..preorder(4)
4
4 15
....preorder(3)
3
3 9 18 ......preorder(NULL)
......preorder(NULL)
7 16 20
....preorder(9)
9
5 17
......preorder(7)

void preorder(TreeNode<int>* treeNode) 7


{ ........preorder(5)
if( treeNode != NULL ) 5
Fig 14.1 (a) : preorder recursion
{
cout << *(treeNode->getInfo())<<" "; ..........preorder(NULL)
preorder(treeNode->getLeft()); ..........preorder(NULL)
preorder(treeNode->getRight());
........preorder(NULL)
}
} ......preorder(NULL)
..preorder(15)
Preorder Recursion 15
14 ....preorder(NULL)
....preorder(18)
18
15
4 ......preorder(16)
16
........preorder(NULL)
3 9 18
........preorder(17)
17
7 16 20 ..........preorder(NULL)
..........pre3
5 17 der(NULL)
......preord er(20)
void preorder(TreeNode<int>* treeNode) 20
{ ........preorder(NULL)
if( treeNode != NULL ) ........preorder(NULL)
{ Fig 14.1 (b): preorder recursion

cout << *(treeNode->getInfo())<<" ";


preorder(treeNode->getLeft());
preorder(treeNode->getRight());
}
}
Tree implementation
struct node
{
int data;
struct node* left;
struct node* right;
};

Tree implementation
struct node* Createnode(int data)

{
struct node* node = (struct node*)
malloc(sizeof(struct node));

node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}
Tree implementation
void Preorder(struct node* node)
{
if (node == NULL)
return;
cout<< node->data<<" ";
Preorder(node->left);
Preorder(node->right);
}
• In order and Post order Traversals do it by yourself
Applications of Binary Tree
 Binary tree is useful structure when two-way decisions are made at each
point. Suppose we want to find all duplicates in a list of the following
numbers:

14, 15, 4, 9, 7, 18, 3, 5, 16, 4, 20, 17, 9, 14, 5

 This list may comprise numbers of any nature. For example, roll numbers,
telephone numbers or voter’s list. In addition to the presence of duplicate
number, we may also require the frequency of numbers in the list. As it is a
small list, so only a cursory view may reveal that there are some duplicate
numbers present in this list. Practically, this list can be of very huge size
ranging to thousands or millions.
Binary Search Trees
• Stores keys in the nodes in a way so that searching, insertion and
deletion can be done efficiently.
Binary search tree property
• For every node X, all the keys in its left subtree are smaller than the key value
in X, and all the keys in its right subtree are larger than the key value in X
Binary Search Trees

A binary search tree Not a binary search tree


Why?
Creating Binary Search Tree

• The first number in the list is placed in a node, designated as the


root of the binary tree.
• Initially, both left and right sub-trees of the root are empty. We take
the next number and compare it with the number placed in the
root. If it is the same, this means the presence of a duplicate (do
nothing).
• Otherwise, we create a new tree node and put the new number in
it. The new node is turned into the left child of the root node if the
second number is less than the one in the root. The new node is
turned into the right child if the number is greater than the one in
the root.
Creating Binary Search Tree
14

14, 15, 4, 9, 7, 18, 3, 5, 16, 4, 20, 17, 9, 14, 5

First number in the list became the root

15 14

14, 15, 4, 9, 7, 18, 3, 5, 16, 4, 20, 17, 9, 14, 5

A new node is created to insert it in the binary tree

14

15

14, 15, 4, 9, 7, 18, 3, 5, 16, 4, 20, 17, 9, 14, 5

The second node is added into the tree


Creating Binary Search Tree
14
4 14

4 15
15

14, 15, 4, 9, 7, 18, 3, 5, 16, 4, 20, 17, 9, 14, 5 14, 15, 4, 9, 7, 18, 3, 5, 16, 4, 20, 17, 9, 14, 5

A new node is created and number 4 put into it The node is added as the left child of the root node

14

4 15

14, 15, 4, 9, 7, 18, 3, 5, 16, 4, 20, 17, 9, 14, 5

A new node is added in the tree


Creating Binary Search Tree
14

4 15

3 9 18

7 16 20

5 17

14, 15, 4, 9, 7, 18, 3, 5, 16, 4, 20, 17, 9, 14, 5

Binary tree of whole list of numbers


Searching BST
• If we are searching for 15, then we are done.
• If we are searching for a key < 15, then we should search in the left subtree.
• If we are searching for a key > 15, then we should search in the right
subtree.
Three BST search algorithms:

• Find the smallest node


• Find the largest node
• Find a requested node
BST Insertion

• To insert data all we need to do is follow the branches to an empty


subtree and then insert the new node.
• In other words, all inserts take place at a leaf or at a leaflike node –
a node that has only one null subtree.
30 30

30 30
Searching for Duplicates
 One way of finding duplicates is to compare each number with all those
that precede it.

14, 15, 4, 9, 7, 18,


4, 3, 5, 16, 4, 20, 17, 9, 14, 5

14, 15, 4, 9, 7, 18,


4, 3, 5, 16, 4, 20, 17, 9, 14, 5

Fig 12.1: Search for Duplicates

 So, the solution lies in reducing the number of comparisons. The number of
comparisons can be drastically reduced with the help of a binary tree. The
benefits of linked list are there, also the tree grows dynamically like the
linked list.
Deletion in Binary Search Tree
• When we delete a node, we need to consider how we take care of
the children of the deleted node.
• This has to be done such that the property of the search tree is
maintained.
Deletion in Binary Search Tree
Three cases:
(1) the node is a leaf
• Delete it immediately

2 8

1 4

3
Deletion in Binary Search Tree
(2) the node has one child
• Adjust a pointer from the parent to bypass that node and connect to inorder
successor.

6 6 6

2 8 2 8 2 8

1 4 1 4 1 3

3 3

Deletion in steps
Deletion in Binary Search Tree
(3) the node has 2 children
• The strategy s to replace the data of this node containing the smallest data of
the right sub-tree and recursively delete that node.
• delete the minimum element
• Has either no child or only right child because if it has a left child, that left
child would be smaller and would have been chosen. So invoke case 1 or 2.

6
6 6 6 6

3 8
2 8 3 8 3 8 3 8

1 5
1 5 1 5 1 5 1 5
3
3 3 3
4
4
4 4 4
Inorder
successor

Delete (2) - remove the in order successor


BST implementation
struct node
{
int key;
struct node *left, *right;
};
BST implementation
• Implement Create node function
• Implement Inorder traversal function
• As we did in binary tree
Insert
struct node* insert(struct node* node, int key)
{ if (node == NULL) return CreateNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);
return node;
}
Find minimum
int minValue(struct node* node) {
struct node* current = node;

while (current->left != NULL) {


current = current->left;
}
return(current->data);
}
Deletion
• struct node* deleteNode(struct node* root, int key)
•{
• // base case
• if (root == NULL) return root;
• if (key < root->key)
• root->left = deleteNode(root->left, key);
• Else if //same for right

/node with only one child or no child

• else {
• if (root->left == NULL)
• {
• struct node *temp = root->right;
• free(root);
• return temp;
• }
• Implement for right same as left
Node with two children:

• struct node* temp = minValueNode(root->right);


• root->key = temp->key;
• root->right = deleteNode(root->right, temp->key);
• }
• return root;
•}

You might also like