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

Trees - Binary Tree and (Binary Search Tree)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Trees - Binary Tree and (Binary Search Tree)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 107

Data Structures and Algorithms

I
T
2
0 Data Structure
8
Lecture
11 Dr. Belal Murshed
Data Structures and Algorithms

I
T
2 Trees
0
8
Introduction

2 Dr. Belal Murshed


Data Structures and Algorithms

Trees - Introduction
• Arrays
I
• Linked List
T
2
• Stacks
0
• Queues
8
• Tree
• Graph
3 Dr. Belal Murshed
Data Structures and Algorithms

Trees - Introduction
• Definition
I oA tree is a hierarchical data structure that
T organizes data elements, called nodes, by
connecting them with links, called branches
2 Leaves
• Examples
0
oDates Tree
8 oPalm Tree
• Tree has Branches
Roots

4 Dr. Belal Murshed


Data Structures and Algorithms

Trees - Introduction
• Tree in nature consists of Leaves
I oRoots
T oBranches
2 oLeaves
Branches
0 • Tree in Computing Roots

oEdge or Branches Root


8
oNodes Nodes Branch
or edge

5 Left Subtree RightDr.


Subtree
Belal Murshed
Data Structures and Algorithms

Trees - Introduction
• Array’s members
I oElements
T • Element of array

2 • Linked List’s members


oNodes
0 • Node of a linked List
8 • Tree’s members
oNodes
• Node of a tree

6 Dr. Belal Murshed


Data Structures and Algorithms

Trees - Introduction
• Relationship
I oArrays
T • Predecessor - Successor
2 oLinked List
• Predecessor - Successor
0 oTree
8 • Parent - Child

7 Dr. Belal Murshed


Data Structures and Algorithms

Trees - Introduction
• Size Measurement
I o Arrays
• Length of array
T • # of elements i.e. 11
o Linked List
2 • Length of linked list
• # of nodes i.e. 7 Level 0 ……….……..
0 o Tree
• Height or Depth of Tree Level 1….…..
8 • # of edges along longest path
from the root to a leaf in that Level 2 ...
tree
• Height is the maximum distance Level 3 ……..
from root to leaf Hieght=3
• Tree with one node has height 0
8 Dr. Belal Murshed
Data Structures and Algorithms

Trees - Introduction
• Types of Node
I oChild Node
T • A node in a tree can have several successors, which
we refer to as children
2 • 2 & 6 are the children of 5
0 oParent Node
• A node’s predecessor would be its parent
8
• 5 is parent of 2 and 6 & 8 is parent of 7 and 9

9 Dr. Belal Murshed


Data Structures and Algorithms

Trees - Introduction
• Node Types (Cont.)
I oRoot Node
T • A node which has no parent(parentless)
• 5 is the root node
2 oLeaf Node
• A node which has no child (childless)
0
• 1, 3, 7, 9 are leaf nodes
8 oInterior Node
• A node which is neither a root nor a leaf
• 2, 4, 6, 8 are interior nodes

10 Dr. Belal Murshed


Data Structures and Algorithms

Trees - Summary
• Abstract Data Type (ADT)
I • Hierarchical Data Structure
• Nodes
T o Root, Parent, Child, Leaf, Interior
2 • Parent – Child relationship
• Size is measured in terms of height
0 o # of edges from root to leaf along the longest path
• Logical Data Structure
8
• Implementation
o Array
o Linked List

11 Dr. Belal Murshed


Data Structures and Algorithms

I
T
2 Trees
0
8
Types of Tree

12 Dr. Belal Murshed


Data Structures and Algorithms

Trees - Introduction
• Types of Tree
I oGeneral Tree
T • Any number of roots
• Any number of children
2 per node
0 oBinary Tree
• Only one root
8
• Maximum 2 children per
node

13 Dr. Belal Murshed


Data Structures and Algorithms

General Trees - Introduction


• Tree Traversal
I oDepth First Search (DFS)
T • It explores a path all the way to a leaf before
backtracking and exploring another path
2 oBreadth First Search (BFS)
0 • It explores all nodes nearest the root before
exploring nodes further away
8

14 Dr. Belal Murshed


Data Structures and Algorithms

General Trees - Introduction


Depth First Search (DFS) A
I • It explores a path all the
way to a leaf before B C
T backtracking and
2 exploring another path.
D E F G
• The algorithm starts at
0 o (1) the root node and
8 o (2) explores the left and H I J K
right subtrees by going
deeper into the tree as it
processes nodes. L M N O P Q
A B D E H L M N I O P C F G J K Q
15 Dr. Belal Murshed
Data Structures and Algorithms

General Trees - Introduction


A
• Breadth First
I Search (BFS)
B C
T oIt explores all
2 nodes nearest
the root before D E F G
0 exploring nodes
8 further away H I J K

L M N O P Q
A B C D E F G H I J K L M N O P Q
16 Dr. Belal Murshed
Data Structures and Algorithms

I
T
2 Binary Trees
0
8
Introduction

17 Dr. Belal Murshed


Data Structures and Algorithms

Binary Tree - Introduction


• Definition
I oA tree in which each node can have a
T maximum of two children
• Each node can have no child, one child, or two
2 children
0 • And a child can only have one parent

18 Dr. Belal Murshed


Data Structures and Algorithms

Binary Tree - Introduction


• Level
I oLevel of a node is the number of edges
T between the node and the root
2 oRoot is at level 0

0
8

19 Dr. Belal Murshed


Data Structures and Algorithms

Binary Tree - Introduction


• Maximum nodes at any level
I oLevel “i”
T oN = 2i
• i=0
2 • N = 20 = 1
• i=1
0 • N = 21 = 2
• i=2
8 • N = 22 = 4
• i=3
• N = 23 = 8

20 Dr. Belal Murshed


Data Structures and Algorithms

Binary Tree - Introduction


• Sub Tree
I oA Sub Tree of a tree T, is a tree consisting of a
T node in T, and all of its children (descendants).
2
• Left Subtree
0
• Right Subtree
8

21 Dr. Belal Murshed


Data Structures and Algorithms

Binary Tree - Introduction


• Full Binary Tree
I oEvery node, other than the leaves, has two
T children exactly. and a node cannot have just
one child. a
2
0
b c
8 g, h, e, and c are
leaves: so they
d e have no children.

22
g h Dr. Belal Murshed
Data Structures and Algorithms

Binary Tree - Introduction


• Complete Binary Tree
I oEvery level, except possibly the last, is
T completely filled, and all nodes are as far left
as possible.
2
0
8

23 Dr. Belal Murshed


Data Structures and Algorithms

Binary Tree - Introduction


• Complete Binary Tree
I oEvery level, except possibly the last, is
T completely filled, and all nodes are as far left
as possible.
2
0
8

24 Dr. Belal Murshed


Data Structures and Algorithms

Binary Tree - Introduction


Complete Binary Tree
• Counting maximum number of node at 𝒊𝒕𝒉 𝐥eve
I
o Number of nodes at level 0:1 : 20
T o Number of nodes at level 1:2 : 21
2 o Number of nodes at level 2:4 : 22
o Number of nodes at level 3:8 : 23
0 o Number of nodes at level 4 : 16 : 24
o Number of nodes at level 5 : 32 : 25
8 . .
. .
o Number of nodes at level i : 1 : 2𝑖

25 Dr. Belal Murshed


Data Structures and Algorithms

Binary Tree - Introduction


:- Total Number of nodes in binary tree with height h
I 𝑛 = 20 +21 +22 +23 +24 ………+2ℎ
2ℎ+1 −1
𝑛= => 𝒏 = 𝟐𝒉+𝟏 − 𝟏
T 2−1

𝒏 = 𝟐𝒉+𝟏 − 𝟏 ⇒ n + 1 = 2ℎ+1
2 log(n + 1) = log 2ℎ+1
0 log(n + 1) = h + 1 𝑙𝑜𝑔2
ℎ + 1 = 𝑙𝑜𝑔2 (𝑛 + 1)
8 ℎ = 𝑙𝑜𝑔2 𝑛 + 1 − 1
ℎ = 𝑙𝑜𝑔2 𝑛 + 1 − 1 ⇒ ℎ = 𝑙𝑜𝑔2 𝑛 + 1
upper Below
𝒉 = 𝒍𝒐𝒈𝟐 𝒏 ,
𝒉 𝑖𝑠 𝑡ℎ𝑒 𝑚𝑖𝑛𝑖𝑚𝑢𝑚 𝒍𝒐𝒈𝟐 𝒏
26 Dr. Belal Murshed
Data Structures and Algorithms

Binary Tree - Introduction


• Complete Binary Tree
I • Height
T • h = floor(log2 15)
• h = floor(3.906) = 3
2 • h = floor(log2 11)
0 • h = floor(3.459) = 3
• h = floor(log2 4)
8 • h = floor(2) = 2
• h = floor(log2 1)
• h = floor(0) = 0

27 Dr. Belal Murshed


Data Structures and Algorithms

Binary Tree - Introduction


• Complete Binary Tree
I • Max. no. of nodes
T oN = 2h+1 - 1
• N = 23+1 – 1= 24 – 1
2 • =16 - 1 = 15
• N = 22+1 – 1= 23 – 1
0 • =8 - 1 = 7
8 • N = 21+1 – 1= 22 – 1
• =4 - 1 = 3
• N = 20+1 – 1= 21 – 1
• =2 - 1 = 1
28 Min. # of nodes => N = 2h Dr. Belal Murshed
Data Structures and Algorithms

I
T
2 Binary Trees
0
8
Traversal

29 Dr. Belal Murshed


Data Structures and Algorithms

Binary Tree - Introduction


root
• Binary Tree Traversal a
I
• It is designed Based on DFS
T o3 - variants b c
2 • Pre Order Pre Order:
o Root – Left - Right a b c
0 • In Order In Order:
8 o Left – Root - Right b a c
• Post Order Post Order:
o Left – Right - Root b c a

30 Dr. Belal Murshed


Data Structures and Algorithms

Binary Tree Traversal – Pre Order


root

• Pre Order
I oRoot – Left - Right
T
2
0
8 Traversal: a b d g h e i c f j

31 Dr. Belal Murshed


Data Structures and Algorithms

Binary Tree Traversal – In Order


root

• In Order
I oLeft - Root –Right
T
2
0
8 Traversal: g d h b e i a f j c

32 Dr. Belal Murshed


Data Structures and Algorithms

Binary Tree Traversal – Post Orderroot


• Post Order
I oLeft - Right - Root
T
2
0
8 Traversal: g h d i e b j f c a

33 Dr. Belal Murshed


Data Structures and Algorithms

I
T
2 Binary Trees
0
8
Implementation

34 Dr. Belal Murshed


Data Structures and Algorithms

I
T
2 Binary Trees
0
8
Implementation

35 Dr. Belal Murshed


Data Structures and Algorithms

Binary Tree - Implementation


• A binary tree has a natural implementation using
I linked storage i.e. Linked List
T • Each node of a binary tree has both left and right
subtrees that can be reached with pointers.
2
• Double Linked List
0
left_child data right_child
8

36 Dr. Belal Murshed


Data Structures and Algorithms

BinaryTree
// A binary tree node has data, pointer to left child
// and a pointer to right child
I struct Node {
int data;
T struct Node *left, *right;
};
2
// Utility function to create a new tree node
0 Node* newNode(int data)
{
8 Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
37 Dr. Belal Murshed
Data Structures and Algorithms

Inorder BinaryTree
// Given a binary tree, print its nodes in inorder
void printInorder(struct Node* node)
I {
if (node == NULL)
T return;

2 // First recur on left child


printInorder(node->left);
0
// Then print the data of node
8 cout << node->data << " ";

// Now recur on right child


printInorder(node->right);
}
38 Dr. Belal Murshed
Data Structures and Algorithms

BinaryTree
// Driver code
int main()
I {
struct Node* root = newNode(1);
T root->left = newNode(2);
root->right = newNode(3);
2 root->left->left = newNode(4);
root->left->right = newNode(5);
0
// Function call
8 cout << "Inorder traversal of binary tree is \n";
printInorder(root);

return 0;
}
39 Dr. Belal Murshed
Data Structures and Algorithms

I
T Binary Tree
2 Implementation
0
8
Traversal

40 Dr. Belal Murshed


Data Structures and Algorithms

Binary Tree – In Order


• Left - Root –Right
I
• the root is visited between the left and
T right sub trees
2 Algorithm inorder (BTnode *node)
method
0 if (node = NULL) then
Return
8 ifend
inorder(node->left)
print node->data
inorder(node->right)
Algend
41 Dr. Belal Murshed
Data Structures and Algorithms

Binary Tree – Pre Order


• Root – Left – Right
I
• The root is visited before its left and right
T sub trees
2 Algorithm preorder (BTnode node)
method
0 if (node = NULL) then
Return
8 ifend
print node->data + “ ”
preorder(node->left)
preorder(node->right)
Algend
42 Dr. Belal Murshed
Data Structures and Algorithms

Binary Tree – Post Order


• Left - Right - Root
I
• the root is visited after both the left and
T right sub trees
2 Algorithm postorder (BTnode node)
method
0 if (node = NULL) then
Return
8 ifend
postorder(node->left)
postorder(node->right)
print node->data
Algend
43 Dr. Belal Murshed
Data Structures and Algorithms

I
T Binary Tree
2 Implementation
0
8
Searching

44 Dr. Belal Murshed


Data Structures and Algorithms

Binary Tree - Searching


• Searching for a node in an arbitrary tree
I • If found return “true” otherwise “false”
• Searching will take O(n) time
T
boolean searchTree( BTnode node, int data ) {
2 if (node == null) {
return false;
}
0 if (data == node->data) {
return true;
8 }

return searchTree(node->left, data) || searchTree(node->right,


data);
}

45 Dr. Belal Murshed


Data Structures and Algorithms

I
T
Binary Search Tree
2 (BST)
0
8
Introduction

46 Dr. Belal Murshed


Data Structures and Algorithms

BST - Introduction
• Value of left child is
I smaller than root
T • Value of right child is
2 greater or equal to the
0 root
8 • This order property is
applicable to each and
every node
47 Dr. Belal Murshed
Data Structures and Algorithms

BST - Introduction
44

I
24 65
T
2 56 88
20 36
0
8 15 28 40 62

8 19 30 42 58 64

48 Dr. Belal Murshed


Data Structures and Algorithms

BST - Introduction
• Summary
I oSearching is efficient
T
2 oLeft child is always smaller
0
oRight child is always greater or equal
8
oSearching will take O (log2 n)

49 Dr. Belal Murshed


Data Structures and Algorithms

I
T
Binary Search Tree
2 (BST)
0
8
Operations

50 Dr. Belal Murshed


Data Structures and Algorithms

BST - Operations
• Traversal
I oAccessing/visiting all values of a tree once
T • Searching
oFinding a key value
2 • Insertion
oAdding a value in a tree
0
• Deletion
8 oRemoving a value from tree
• Creation
oCreating a tree from empty tree
51 Dr. Belal Murshed
Data Structures and Algorithms

BST - Traversal
• Pre Order Traversal
I o8,3,1,6,4,7,10,14,13
T • In Order Traversal
o1,3,4,6,7,8,10,13,14
2 • Post Order Traversal
o1,4,7,6,3,13,14,10,8
0
• Depth First Search
8 o8,3,1,6,4,7,10,14,13
• Breadth First Search
o8,3,10,1,6,14,4,7,13
52 Dr. Belal Murshed
Data Structures and Algorithms

BST - Searching
• Order Property should be followed
I 1) Start from root
2) Compare with root
T 3) Go right if the key value is greater than or equal
to root
2 4) Go left if the key value is less than the root
0 • Keep doing this till you find it
• return True
8 • or reach to an empty position
o return False

53 Dr. Belal Murshed


Data Structures and Algorithms

BST - Searching
• Key = 6 root
I oTrue
T • Key = 13
2 oTrue
0 • Key = 0
8 oFalse
• Key = 20
oFalse
54 Dr. Belal Murshed
Data Structures and Algorithms

BST - Insertion
• Order Property should be maintained
I 1) Start from root
T 2) Go right if the new value is greater than or
2 equal to the root
3) Go left if the new value is less than the root
0 4) Keep doing this till you come to an empty
8 position
• Insert the value

55 Dr. Belal Murshed


Data Structures and Algorithms

BST - Insertion
• Key = 0 root
I oNull
T • Key = 30
2 oNull
0
8

56 Dr. Belal Murshed


Data Structures and Algorithms

BST - Deletion
• There are 3 possible cases
I oDeletion of a leaf node
T
2 oDeleting a node with one child
0
oDeleting a node with two children
8

57 Dr. Belal Murshed


Data Structures and Algorithms

BST - Deletion – Leaf Node 12


• Identify the parent of the node
I • parent.left = null; or
• or parent.right = null;
T 10 10

2 6 14 6 14
0
4 8 12 18 4 8 18
8
2 16 2 16

Dr. Belal Murshed


Data Structures and Algorithms

BST - Deletion – Node with One Child


• Identify the parent of the node
I
T • The parent’s pointer is changed to the
2 deleted node’s child
0
8 • This has the effect of lifting up the deleted
nodes child by one level in the tree

Dr. Belal Murshed


Data Structures and Algorithms

BST - Deletion – Node with One Child


• Identify the parent of the node
I o parent.left = parent.left.left;
o Or parent.left = parent.left.right;
T
10 10
2
6 14
0 6 14

8 4 8 12 18 2 8 12 18

2 16 16

Dr. Belal Murshed


Data Structures and Algorithms

BST - Deletion – Node with One Child


• Identify the parent of the node
I o parent.right = parent.right.right;
o Or parent.right = parent.right.left;
T
10
2 10

6 14
0 6 18

8 4 8 18
4 8 16

2 16 15 17
2

15 17
Dr. Belal Murshed
Data Structures and Algorithms

BST - Deletion – Node with TWO children


• Identify the parent
I
• Replace the node to be deleted
T oLargest value of left subtree
2 • Right most node of the left child
0 OR
oSmallest value of Right subtree
8 • Left most node of right child

62 Dr. Belal Murshed


Data Structures and Algorithms

BST - Deletion – Node with TWO children


59
• Identify the parent 18 67
I
• Replace the node to be deleted 13 32 63 72
T oLargest value of left subtree 10 15 25 43
2 • Right most of the left child
0 OR
oSmallest value of Right subtree
8 • Left most of right child

63 Dr. Belal Murshed


Data Structures and Algorithms

BST - Deletion – Node with TWO children


59
• Identify the parent 18 67
I
• Replace the node to be deleted 13 32 63 72
T oLargest value of left subtree 10 15 25 43
2 • Right most of the left child
59
0
15 67
8
13 32 63 72

10 25 43
64 Dr. Belal Murshed
Data Structures and Algorithms

BST - Deletion – Node with TWO children


• Identify the parent 59
I
• Replace the node to be deleted 18 67
T oSmallest value of Right subtree 13 32 63 72

2 • Left most of right child 10 15 25 43

0 59

8 25 67

13 32 63 72

10 15 43
65 Dr. Belal Murshed
Data Structures and Algorithms

BST - Deletion – Node with TWO children


• Largest value of left subtree 59
I oAt most have ONE child 18 67
T oOnly left child 13 32 63 72

2 10 15 25 43

0
8

66 Dr. Belal Murshed


Data Structures and Algorithms

BST - Deletion – Node with TWO children


• Smallest value of left subtree 59
I oAt most have ONE child 18 67
T oOnly right child 13 32 63 72

2 10 15 25 43

0
8

67 Dr. Belal Murshed


Data Structures and Algorithms

BST - Creation
• Creating a BST is really nothing more than a
I series of insertions (calling the insert
T method over and over)
2 oCreate a new node
oCall the insertion method
0
oNew node will be inserted as a leaf
8 oRepeat this process as long as you want to
insert

68 Dr. Belal Murshed


Data Structures and Algorithms

BST - Creation
• Let’s assume we insert the following data
I values, in their order of appearance into
T an initially empty BST:
10
10, 14, 6, 2, 5, 15, and 17
2
0  Step 1:
 Create a new node with value 10
8  Insert node into tree
 The tree is currently empty
 New node becomes the root

Dr. Belal Murshed


Data Structures and Algorithms

BST - Creation
10, 14, 6, 2, 5, 15, and 17
I
T  Step 2:
 Create a new node with value 14 10
2  This node belongs in the right subtree of
node 10 14
0  Since 14 > 10

 The right subtree of node 10 is empty


8  So node 14 becomes the right child

of node 10

Dr. Belal Murshed


Data Structures and Algorithms

BST - Creation
10, 14, 6, 2, 5, 15, and 17
I
 Step 3:
T  Create a new node with value 6 10
2  This node belongs in the left subtree of
node 10
6 14
0  Since 6 < 10

 The left subtree of node 10 is empty


8  So node 6 becomes the left child of

node 10

Dr. Belal Murshed


Data Structures and Algorithms

BST - Creation
10, 14, 6, 2, 5, 15, and 17
I  Step 4:
 Create a new node with value 2
T  This node belongs in the left subtree of 10
node 10
2  Since 2 < 10
6 14
0  The root of the left subtree is 6
 The new node belongs in the left subtree
8 of node 6 2
 Since 2 < 6

 So node 2 becomes the left child of node 6

Dr. Belal Murshed


Data Structures and Algorithms

BST - Creation
10, 14, 6, 2, 5, 15, and 17
I  Step 5:
T  Create a new node with value 5
10
 This node belongs in the left subtree of
2 node 10
 Since 5 < 10 6 14
0  The new node belongs in the left subtree
of node 6
8  Since 5 < 6
2

 And the new node belongs in the right


subtree of node 2 5
 Since 5 > 2

Dr. Belal Murshed


Data Structures and Algorithms

BST - Creation
10, 14, 6, 2, 5, 15, and 17
I  Step 6:
 Create a new node with value 15
T  This node belongs in the right subtree of 10
node 10
2  Since 15 > 10
6 14
0  The new node belongs in the right
subtree of node 14
8  Since 15 > 14 2 15
 The right subtree of node 14 is empty
 So node 15 becomes right child of node 5
14

Dr. Belal Murshed


Data Structures and Algorithms

BST - Creation
10, 14, 6, 2, 5, 15, and 17
I  Step 7:
 Create a new node with value 17
T  This node belongs in the right subtree of 10
node 10
2  Since 17 > 10
6 14
0  The new node belongs in the right
subtree of node 14
8  Since 17 > 14 2 15
 And the new node belongs in the right
subtree of node 15 5 17
 Since 17 > 15

Dr. Belal Murshed


Data Structures and Algorithms

I
T
Binary Search Tree
2 (BST)
0
8
Implementation

76 Dr. Belal Murshed


Data Structures and Algorithms

Binary Search Tree – Node Class


public class intBSTnode {
public int data;
I public intBSTnode left;
public intBSTnode right;
T public intBSTnode () {
left = right = null;
2 }
public intBSTnode (int i) {
this(i, null, null);
0 }
public intBSTnode (int i, intBSTnode n, intBSTnode p) {
8 data = i;
left = n;
right = p;
}
}

77 Dr. Belal Murshed


Data Structures and Algorithms

Class – BinarySearchTree
public class BinarySearchTree {
private intBSTnode root;
I
// Constructor
T public BinarySearchTree() {

2 root = null;
}
0
8 }
// All methods will be written here

78 Dr. Belal Murshed


Data Structures and Algorithms

I
T
2 Binary Search Tree
0
8
Operations

79 Dr. Belal Murshed


Data Structures and Algorithms

BST - Operations
• Traversal
I oAccessing/visiting all values of a tree once
T • Searching
oFinding a key value
2 • Insertion
oAdding a value in a tree
0
• Deletion
8 oRemoving a value from tree
• Creation
oCreating a tree from empty tree
80 Dr. Belal Murshed
Data Structures and Algorithms

BST - Traversal
I
• Pre Order Traversal
T
• In Order Traversal
2
• Post Order Traversal
0
• Depth First Search
8
• Breadth First Search

81 Dr. Belal Murshed


Data Structures and Algorithms

BST – Post Order


• Left - Right - Root
I
• the root is visited after both the left and
T right sub trees
2 public void postorder (intBSTnode p) {
if (p != NULL) {
0 postorder(p.left);
postorder(p.right);
8 System.out.print(p.data + “ ”);
}
}

82 Dr. Belal Murshed


Data Structures and Algorithms

I
T
2 Binary Search Tree
0
8
Searching
(Iterative Solution)

83 Dr. Belal Murshed


Data Structures and Algorithms

BST – Searching -Iterative


public intBSTnode (int key) {
intBSTnode current = root;
I while (current.data != key) {
if (key < current.data)
T current = current.left;
else
2 current = current.right;
if (current == null);
0 return null;
}
8 return current;
}

84 Dr. Belal Murshed


Data Structures and Algorithms

BST – Searching - Tracing


public intBSTnode find(int key) {
intBSTnode current = root; root
I
while (current.data != key) {
if (key < current.data)
current = current.left;
T else
current = current.right;
2 if (current == null);
return null;
}
0
return current;
}
8

85 Dr. Belal Murshed


Data Structures and Algorithms

I
T
2 Binary Search Tree
0
8
Searching
(Recursive Solution)

86 Dr. Belal Murshed


Data Structures and Algorithms

BST – Searching -Recursive


public boolean recurSearch(intBSTnode p, int data) {
if (p == null)
I return(false);
if (data == p.data)
T return(true);
else if (data < p.data)
2 return(recurSearch(p.left, data));
else
0 return(recurSearch(p.right, data));
}
8

87 Dr. Belal Murshed


Data Structures and Algorithms
public boolean recurSearch(intBSTnode p, int data) {

}
BST – Searching - Recursive
if (p == null) {
return(false);

if (data == p.data) {
return(true); root
}
I
else if (data < p.data) {
return(recurSearch(p.left, data));
}
T
else {
return(recurSearch(p.right, data));
}
} 2
0
8

88 Dr. Belal Murshed


Data Structures and Algorithms

I
T
2 Binary Search Tree
0
8
Insertion

89 Dr. Belal Murshed


Data Structures and Algorithms

BST – Insertion
public intBSTnode insert(intBSTnode p, int data) {
if (p == null) {
I p = new intBSTnode(data);
}
T else {
if (data < p.data) {
2 p.left = insert(p.left, data);
}
0 else {
p.right = insert(p.right, data);
8 }
}

return p;
}

90 Dr. Belal Murshed


Data Structures and Algorithms

BST – Insertion - Tracing


public intBSTnode insert(intBSTnode p, int data) {
if (p == null) { root
p = new intBSTnode(data);
}I
else {
if (data < p.data) {
T }
p.left = insert(p.left, data);

else {
2 }
p.right = insert(p.right, data);

}
0
return p;

91 Dr. Belal Murshed


Data Structures and Algorithms

I
T
2 Binary Search Tree
0
8
Deletion

92 Dr. Belal Murshed


Data Structures and Algorithms

BST – Deletion
• Find node to be deleted
I
• Find Parent of node
T
• Check node is a “leaf”
2
• Has only Left Child
0
• Has only Right Child
8
• Find Smallest node
• Find Largest node
93 Dr. Belal Murshed
Data Structures and Algorithms

BST – Deletion - Find Node to Delete


public BSTnode findNode(int data) {
return findNode(root, data);
I }
private BSTnode findNode(BSTnode p, int data) {
T if (p == null)
return null;
2 else {
if (data == p.getData())
0 return p;
else if (data <p.getData())
8 return findNode(p.getLeft(), data);
else
return findNode(p.getRight(), data);
}
}
94 Dr. Belal Murshed
Data Structures and Algorithms

BST – Deletion – Find Node to Delete


public BSTnode findNode(int data) {
return findNode(root, data);
}

I private BSTnode findNode(BSTnode p, int data) {


if (p == null)
return null;

T else {
if (data == p.getData())
return p;
else if (data <p.getData())
2 return findNode(p.getLeft(), data); 59
else
return findNode(p.getRight(), data);
0 }
18 67
}

8
13 32 63 72

10 15 25 43

95 Dr. Belal Murshed


Data Structures and Algorithms

BST – Deletion - Find Parent Node


public BSTnode parent(BSTnode p) {
return parent(root, p);
I }
private BSTnode parent(BSTnode root, BSTnode p) {
T if (root == null || root == p)
return null;
2 if (root.getLeft()==p || root.getRight()==p)
return root;
0 if (p.getData() <root.getData())
return parent(root.getLeft(), p);
8 else if (p.getData() >root.getData())
return parent(root.getRight(), p);
else
return null;
}
96 Dr. Belal Murshed
Data Structures and Algorithms

BST – Deletion - Find Parent Node


public BSTnode parent(BSTnode p) {
return parent(root, p);
} I
private BSTnode parent(BSTnode root, BSTnode p) {
if (root == null || root == p)
T return null;
if (root.getLeft()==p || root.getRight()==p)
2 return root;
if (p.getData() <root.getData())
return parent(root.getLeft(), p); 59
0
else if (p.getData() >root.getData())
return parent(root.getRight(), p);
18 67
else
8 return null;
} 13 32 63 72

10 15 25 43

97 Dr. Belal Murshed


Data Structures and Algorithms

BST – Deletion – Leaf Node


public boolean isLeaf(BSTnode p) {
return (p.getLeft()==null && p.getRight()==null);
I }

T
59
2
18 67
0
13 32 63 72
8
10 15 25 43

98 Dr. Belal Murshed


Data Structures and Algorithms

BST – Deletion – Has Left Child only


public Boolean hasOnlyLeftChild(BSTnode p) {
return (p.getLeft()!=null &&p.getRight()==null);
I }

T
59
2
18 67
0
13 32 63 72
8
10 15 25 43

99 Dr. Belal Murshed


Data Structures and Algorithms

BST – Deletion – Has Right Child only


public Boolean hasOnlyRightChild(BSTnode p) {
return (p.getLeft()==null &&p.getRight()!=null);
I }

T
59
2
18 67
0
13 32 63 72
8
10 15 25 43

100 Dr. Belal Murshed


Data Structures and Algorithms

BST – Deletion – Find Smallest Node


public BSTnode minNode(BSTnode root) {
if (root == null)
I return null;
else if (root.getLeft() == null)
T return root;
else
2 return minNode(root.getLeft())
} 59
0
18 67
8
13 32 63 72

10 15 25 43

101 Dr. Belal Murshed


Data Structures and Algorithms

BST – Deletion – Find Largest Node


public BSTnode maxNode(BSTnode root) {
if (root == null)
I return null;
else if (root.getRight() == null)
T return root;
else
2 return maxNode(root.getRight());
} 59
0
18 67
8
13 32 63 72

10 15 25 43

102 Dr. Belal Murshed


Data Structures and Algorithms
public void delete(int data) {
BST – Deletion
}
root = delete(root, data);

private BSTnode delete(BSTnode p, int data) {


BSTnode node2delete, newnode2delete;
I BSTnode node2save, parent;
int saveValue;
T node2delete = findNode(p, data);
if (node2delete == null)
2 return root;
parent = parent(p, node2delete);
if (isLeaf(node2delete)) {
0 if (parent == null)
return null;
8 if (data < parent.getData())
parent.setLeft(null);
else
parent.setRight(null);
return p;
103 } Dr. Belal Murshed
Data Structures and Algorithms
if (hasOnlyLeftChild(node2delete)) {
BST – Deletion
if (parent == null)
return node2delete.getLeft();
if (data <parent.getData())
parent.setLeft(parent.getLeft().getLeft());
I else
parent.setRight(parent.getRight().getLeft());
T return p;
}
2 if (hasOnlyRightChild(node2delete)) {
if (parent == null)
return node2delete.getRight();
0 if (data <parent.getData())
parent.setLeft(parent.getLeft().getRight());
8 else
parent.setRight(parent.getRight().getRight());
return p;
}

104 Dr. Belal Murshed


Data Structures and Algorithms

BST – Deletion
newnode2delete = minNode(node2delete.getRight());
I saveValue = newnode2delete.getData();
p = delete(p, saveValue);
T node2delete.setData(saveValue);
return p;
2 }

0
8

105 Dr. Belal Murshed


Data Structures and Algorithms

I
T
2
0
8 Allah (Alone) is Sufficient for us,
and He is the Best Disposer of
affairs (for us).(Quran 3 : 173)

106 Dr. Belal Murshed


Data Structures and Algorithms

I
T
2
0
8

107 Dr. Belal Murshed

You might also like