You are on page 1of 39

Binary Trees

Chapter 6
By Efa T.
Introduction to Tree

 In computing, various data structures help in arranging data in different forms.


 Among them, trees are widely used abstract data structures that simulate a hierarchical
tree structure.
 A tree usually has a root value and subtrees that are formed by the child nodes from its
parent nodes.
 Trees are non-linear data structures.
 A tree data structure has no limitation on the number of child nodes it can hold.
Binary tree

 A binary tree is a non-Linear data structure in which each node can have either 0, 1 or 2
child nodes each.
 Each node consists of:
 Data portion
 Pointer to left child
 Pointer to right child
Binary Tree Components

 There are three binary tree components.


 Every binary tree node has these three components associated
with it.
 It becomes an essential concept for programmers to understand
these three binary tree components:
1) Data element
2) Pointer to left subtree
3) Pointer to right subtree
Benefits of a Binary Tree

 The search operation in a binary tree is faster as compared to other trees


 Only two traversals are enough to provide the elements in sorted order
 It is easy to pick up the maximum and minimum elements
 Graph traversal also uses binary trees
 Converting different postfix and prefix expressions are possible using binary trees
Terminologies Associated with Binary Tree and
Types of Binary Tree
 Root: Topmost node in a tree is called the root.  Leaf/External Node: Leaf nodes are nodes with
no children.
 Node: The node is the termination point in a tree that
contains all the data.  Internal Node: Internal node is the node with at
least one child.
 Edge: Edge is the line that connects one node to another.
 Depth of a Node: The number of edges from the
 Parent node that is connected by a directed edge to root to a node is called the depth of that node.
another node at its lower level is called a parent node.
 Height of a Node: The height of a node is the
 Child: The node to which the parent node is connected number of edges from the node to the deepest
when moving towards the leaf nodes is the child node. leaf.
 Sibling Node: Two nodes present at the same level,  Height of Tree: The height of the tree is the
having the same parents are called sibling nodes. maximum height of any node. The value is the
same as the height of the root node.
Binary Tree

Depth Level
Height

3 0 1

2 1 2

3
1 2
4
0 3
Types of Binary trees

 Full Binary Tree


 Complete Binary tree
 Perfect Binary tree
 Balanced Binary tree
 Skewed Binary tree
 Special Types of Binary Trees
 Binary Search Tree
 Heap
Types of Binary Trees
1. Full Binary Tree 2. . Complete Binary Tree
 It a binary tree that has either zero children or  A binary tree where all the tree levels are filled
two children. entirely with nodes, except the lowest level of the
 Also known as a proper binary tree tree.
 The last or the deepest level should also be filled
from left to right.
 level of the any leaf node is either H or H-1 where
H is the height of the tree.
Types of Binary Trees
3. Perfect Binary Tree 4 . Balanced Binary Tree
 A binary tree is said to be ‘perfect’ if all the  A binary tree is said to be ‘balanced’ if the tree
internal nodes have strictly two children, and height is O(logN), where ‘N’ is the number of
every external or leaf node is at the same level or nodes.
same depth within a tree.
 The height of the left and the right subtrees of
 A perfect binary tree having height ‘h’ has 2h – 1
each node should vary by at most one.
node. Here is the structure of a perfect binary tree:
Binary Search Tree

BST Not BST

 In the above tree, the value of root node is 40, which is


greater than its left child 30 but smaller than right child
of 30, i.e., 55. So, the above tree does not satisfy the
property of Binary search tree. Therefore, the above tree
is not a binary search tree.
Binary Tree Traversal

 A Tree Data Structure can be traversed in following ways:


1. Depth First Search or DFS
i. Inorder Traversal
ii. Preorder Traversal
iii. Postorder Traversal

2. Level Order Traversal or Breadth First Search or BFS


In-order

 Traverse the left subtree 314 0 5 2 6


 Visit the root node
 Traverse the right sub tree
 Repeat until all nodes have been visited. 0

1 2

3
4 5 6
pre-order

 Visit the node


 Traverse the left subtree 0 1 3 4 2 5 6
 Traverse the right sub tree
 Repeat until all nodes have been visited.
0

1 2

3
4 5 6
post-order

Traverse the left subtree


Traverse the right sub tree 3 415 6 2 0
Visit the node
Repeat until all nodes have been visited. 0

1 2

3
4 5 6
Level-Order

Visit the root node 0 1 2 3 4 5 6


visit the left and right child
Traverse the next level in level order
Repeat until all nodes have been visited.

1 2

3
4 5 6
Binary Search Tree
 • In the left subtree of any node, you will find nodes with keys smaller than the node’s key.
 • The right subtree of any node will include nodes with keys larger than the node’s key.
 • The left, as well as the right subtree, will be types of binary search tree.
 • That is, we can iterate through all of the BST values in sorted order.
 • Additionally, duplicate values are not permitted in this data structure.
 • Can be balanced and unbalanced binary tree

Not Binary Search Tree


creating a binary search tree

 To create of binary search tree:


 Suppose the data elements are - 45, 15, 79, 90, 10, 55, 12, 20, 50

First, we have to insert 45 into the tree as the root of the


tree.
Then, read the next element; if it is smaller than the root
node, insert it as the root of the left subtree, and move to
the next element.
Otherwise, if the element is larger than the root node,
then insert it as the root of the right subtree.
BST Operations
• 4. Traversal:
 1. Insertion:
• Visiting and processing all the nodes in the BST in a specific order.
 Adding a new node with a given key value into the BST while
• Common traversal methods include Inorder (left-root-right), Preorder (root-left-
maintaining the BST property. right), and Postorder (left-right-root).
 Compare the key value with the current node and traverse left or • 5. Minimum/Maximum:
right until finding an appropriate spot to insert the new node. • Finding the node with the minimum or maximum key value in the BST.
 2. Search • Traverse to the leftmost node for the minimum value or the rightmost node for the
maximum value.
 Finding a specific key value within the BST.
• 6. Successor/Predecessor:
 Start from the root node and compare the target key with the
• Finding the node with the next smallest or next largest key value in the BST.
current node's key.
• For the successor, go to the right child and then find the leftmost node.
 Move left or right in the tree based on the comparison until
• For the predecessor, go to the left child and then find the rightmost node.
finding a match or reaching a leaf node.
• 7. Height/Size:
 3. Deletion:
• Determining the height of the BST, which is the maximum number of edges from
 Removing a node with a specific key value from the BST. the root to a leaf node.

 Handle different scenarios: a node has no children, a node has one • Counting the number of nodes in the BST.
child, or a node has two children.
 Reorganize the tree while maintaining the BST property.
BST Search Operation

1) First, compare the element to be searched with the root element of the tree.
2) If root is matched with the target element, then return the node's location.
3) If it is not matched, then check whether the item is less than the root element, if it is
smaller than the root element, then move to the left subtree.
4) If it is larger than the root element, then move to the right subtree.
5) Repeat the above procedure recursively until the match is found.
6) If the element is not found or not present in the tree, then return NULL.
BST Search Operation

Suppose we have to find node 20 from the below tree.


Step1 step 2 step
3
Insert Operation

 Inserting a value in the correct position is similar to searching because we try to maintain
the rule that the left subtree is lesser than root and the right subtree is larger than root.

 We keep going to either right subtree or left subtree depending on the value and when we
reach a point left or right subtree is null, we put the new node there.
Deletion Operation
Case I
In the first case, the node to be deleted is the
leaf node. In such a case, simply delete the
node from the tree.
Deletion Operation
Case II
In the second case, the node to be deleted lies
has a single child node. In such a case follow
the steps below:

 Replace that node with its child node.


 Remove the child node from its original
position.
Deletion Operation
Case III
In the third case, the node to be deleted has
two children. In such a case follow the steps
below:

Get the inorder successor of that node.


Replace the node with the inorder successor.
Remove the inorder successor from its
original position.
Deletion Operation
Case III
In the third case, the node to be deleted has
two children. In such a case follow the steps
below:

Get the inorder successor of that node.


Replace the node with the inorder successor.
Remove the inorder successor from its
original position.
Deletion by Merging (continued)

Figure 6-31 The height of a tree can be (a) extended or


(b) reduced after deleting by merging

Data Structures and Algorithms in Java


Deletion by Merging (continued)

Figure 6-31 The height of a tree can be (a) extended or


(b) reduced after deleting by merging (continued)

Data Structures and Algorithms in Java


Binary Search Tree Complexities

Time Complexity Space Complexity


 The space complexity for all the
Average
Operation
Best Case
Case
Worst Case operations is O(n).
Complexity Complexity
Complexity

Search O(log n) O(log n) O(n)

Insertion O(log n) O(log n) O(n)

Deletion O(log n) O(log n) O(n)


Self-Balancing Binary Search Trees

 Self-Balancing Binary Search Trees are height-balanced binary search trees that
automatically keep the height as small as possible when insertion and deletion operations are
performed on the tree.
 The height is typically maintained in order of logN so that all operations take O(logN) time on
average.
 Examples: The most common examples of self-balancing binary search trees are
 AVL Tree
 Red Black Tree and
 Splay Tree
Balancing Binary Tree
 Steps
 Take values at each node and sort them
 Take the middle element and make it root
 Take the left values as list of left subtree nodes
 Take the right values as a list of right subtree nodes
 Repeat the procedure for the left and right values

Balanced Unbalanced
Balance the following unbalanced binary tree
Summary of Binary Tree
 Depth of a node K (of a Binary Tree) = Number of edges in the path connecting the root to the
node K = Number of ancestors of K (excluding K itself).
 Height of a node K (of a Binary Tree) = Number of edges in the longest path connecting K to any leaf node.
 The height of a node in a binary tree is the largest number of edges in a path from a leaf node to a target
node. If the target node doesn’t have any other nodes connected to it, the height of that node would be 0. The
height of a binary tree is the height of the root node in the whole binary tree. In other words, the height of a
binary tree is equal to the largest number of edges from the root to the most distant leaf node.
 A similar concept in a binary tree is the depth of the tree. The depth of a node in a binary tree is the total
number of edges from the root node to the target node. Similarly, the depth of a binary tree is the total
number of edges from the root node to the most distant leaf node.
Summary of Binary Tree

 Follow the steps below to find the height of • Benefits of a Binary Tree
the given node: • The search operation in a binary tree is faster as
compared to other trees
i. If the tree is empty, print -1. • Only two traversals are enough to provide the
elements in sorted order
ii. Otherwise, perform the following steps:
• It is easy to pick up the maximum and minimum
a. Calculate the height of the left subtree elements
recursively. • Graph traversal also uses binary trees
b. Calculate the height of the right subtree • Converting different postfix and prefix
recursively. expressions are possible using binary trees

c. Update height of the current node by adding 1


to the maximum of the two heights obtained in
the previous step. Store the height in a variable,
say ans.
d. If the current node is equal to the given node K,
print the value of ans as the required answer.
Heap

 What is Heap Data Structure?


 A Heap is a special Tree-based data structure in which the tree is a complete binary
tree.
 Heaps can be of two types:
 Max-Heap: In a Max-Heap the key present at the root node must be greatest
among the keys present at all of it’s children. The same property must be
recursively true for all sub-trees in that Binary Tree.
 Min-Heap: In a Min-Heap the key present at the root node must be minimum
among the keys present at all of it’s children. The same property must be
recursively true for all sub-trees in that Binary Tree.
Heap
Operations of Heap Data Structure:

 Heapify: a process of creating a heap from an array.


 Insertion: process to insert an element in existing heap time complexity O(log N).
 Deletion: deleting the top element of the heap or the highest priority element, and then
organizing the heap and returning the element with time complexity O(log N).
 Peek: to check or find the first (or can say the top) element of the heap.

You might also like