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

Lecture 09 - Tree

This document covers the fundamentals of tree data structures, including definitions, terminology, and types of trees such as binary trees and binary search trees. It explains tree operations, traversal methods, and provides algorithms for insertion and traversal in binary trees. Recommended readings and examples are also included to enhance understanding of tree structures and their applications.

Uploaded by

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

Lecture 09 - Tree

This document covers the fundamentals of tree data structures, including definitions, terminology, and types of trees such as binary trees and binary search trees. It explains tree operations, traversal methods, and provides algorithms for insertion and traversal in binary trees. Recommended readings and examples are also included to enhance understanding of tree structures and their applications.

Uploaded by

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

+

CS310 – Data Structure


Lecture – 09 – Tree
2017-2018
+ 2

Objectives
 Idea for Tree
 What is Tree?
 Tree Terminology
 Binary Tree
 TreeTraversing & Examine various Tree
operations
 Learn how to implement a Tree as a linked list
 Discover Tree applications
 Programming Task for Tree structure
February 2, 2025
+ 3

Recommended Readings
 Page – 280: Tree - Chapter 8 - (Data Structure & Algorithm in Java
6th Edition) By GoodRich

 Page – 365: Binary Tree - (Data Structure & Algorithm in Java 2nd
Edition) By Robert Lafore

February 2, 2025
+ 4

Idea for Tree

February 2, 2025
+ What is Tree? 5

 Here are some of the data structures we have studied so far:


 Arrays
 Singly-linked lists and doubly-linked lists
 Stacks, queues, and deques
 These data structure are known as linear data
structure

 These all have the property that their elements can be


displayed in a straight line.

February 2, 2025
+ What is Tree? 6

 Trees are one of the simplest nonlinear data structures that


store elements hierarchically.
 Tree
consists of nodes connected by edges without having any
cycle

 Except
node
the root node, every node
has a parent and zero or more
child nodes.

 Everynode in the tree is the root


of some subtree except leaf node

edges February 2, 2025


+ Some Examples 7


Each linear list is trivially a tree
X
Not a tree: cycle A→A

X X
Not a tree: two non-connected parts,
A→B and C→D→E
Not a tree: cycle B→C→E→D→B February 2, 2025
+ Student Slide (Put √ or X for Tree/non-Tree) 8

February 2, 2025
+ Student Slide (Put √ or X for Tree/non-Tree) 9

X X √
√ X X√ X
February 2, 2025
+ Tree Terminology 10

Many terms are used to describe particular aspects of Trees. A few of


them are

 Root – The node at top of the Tree, there is only one root node in a Tree

 Parent – Any node (except root), that has one edge out to another node

 Child – Any node that have one edge in from the Parent node
Subtree
 Leaf – A node with no children

 Subtree – Any node that consists of


its children and its children’s children

February 2, 2025
+ Tree Terminology 11

 Visiting – A node is visited when program control can access


it.
 Traversing – To visit all the nodes in some specific order
 Path – Walking from node to node along the edges that
connect them
 Edge – Connection between one node to another
 Size – Number of nodes in a
 Depth – The number of edges from node to root
Tree, the Tree size = 9

February 2, 2025
+ Tree Terminology 12

 Levels – Refers to how many generations the node is from


the root
 Keys / Values – The data field is usually designated a key
value
 Height of Tree – the maximum depth among all leaves of
tree T
 Sibling – Nodes with the same parent
 Internal Node – a node with at least one child
Height of Tree
 External Node – a node with no children OR Leaf node

February 2, 2025
Level
+ Students Slide 13

B C

D E F G
I
B is Parent of :

G is Child of :

F is Sibling of: Size of Tree :

Depth of H:
Internal Nodes:
Height:
Leaf: February 2, 2025
Level
+ Students Slide 14

A
0

B C
1

H
2

D E F G
I 3
B is Parent of : D, E

G is Child of : C
Size of Tree : 9
F is Sibling of: G, H
Depth of H: 2
Internal Nodes: 3

D, E, F, G, I Height: 3
Leaf: February 2, 2025
+ 15

Binary Tree

A Binary Tree is either empty or it consists of a node called


the root together with two binary trees called the Left
Subtree and the Right Subtree. [Every node has at most two
children]

February 2, 2025
+ Binary Tree 16

The Binary trees with three nodes are

February 2, 2025
+ Other Kind of Binary Tree 17

A Proper/ Full Binary Tree – “A Binary Tree is Proper/Full if


each node has either zero or two children. Thus, in a Proper
Binary Tree, every internal nodes has exactly two children”

February 2, 2025
+ Binary Tree ADT 18

The tree ADT stores Auxiliary Tree


arbitrary objects (binary operations:
tree: each node can have • boolean isInternal(p)
maximum two children) • boolean isExternal(p)
• boolean isRoot(p)
Main tree operations: Boundary cases:
• Many Traversal() operations Attempting to traverse
• Bool Search(object) an empty Tree , or
• Insert(object) deleting an non-existing
• Delete(object) object will return null

February 2, 2025
+ Binary Tree Implementation - Node Structure 19

The same node structure used for the Linked-List to


represent a Tree. The Node structure used for a Binary Tree
are

Parent
(Address)
Left Right
(Addres Element (Address
s) (Store Data) )

February 2, 2025
+ Binary Tree Representation using Node 20

Parent
Left Right
Element

Left Parent
Right Parent
Element Left Right
Element

Parent
Left Right
Element Parent
Parent Left Right
Left Right
Element
Element Parent
Left Right
Element

February 2, 2025
+ Tree Operations: Traversing 21

A traversal is where each node in a tree is visited once in


some specific order
 For a tree of n nodes there are n! traversals

 There are two very common traversals


 Breadth First (also called level-order)
 Depth First
1. In-order
2. Pre-order
3. Post-order
February 2, 2025
+ Tree Operations: Breadth First Traversal 22

In a breadth first traversal all of the nodes on a given level


are visited and then all of the nodes on the next level are
visited and so on.
 Usually in a left to right fashion

February 2, 2025
+ Tree Operations: Depth First Traversal 23

In a Depth First Traversal all the nodes on a


branch are visited before any others are visited

A binary tree is defined recursively: it consists of a root, a left


subtree, and a right subtree

 Since a binary tree has three “parts”, there are six possible
ways to traverse the binary tree:
 root, left, right  root, right, left
 left, root, right  right, root, left
 left, right, root  right, left, root
February 2, 2025
+ Tree Operations: Depth First Traversal 24

 By standard convention, these are reduced to three by


considering only the ways in which the left subtree is
traversed before the right.

 There are three common Depth First Traversals


 Preorder (root, left, right)
 Inorder (left, root, right)
 Postorder (left, right, root)
Each of these methods is best implemented as a recursive function

February 2, 2025
+ Binary Tree Operations: Depth First – 25

Preorder
Preorder (root, left, right)

 Three recursive steps are followed


 Visit
the root node
 The nodes left subtree is traversed
 The nodes right subtree is traversed

February 2, 2025
+ Binary Tree : Preorder Traversal 26

Algorithm / Java Code


Algorithm: PreOrderPrint
Input: a binary tree node bt
Output: display the tree content in a preorder style

Method:
1. if (bt == null) return;
2. Display(bt.value);
3. PreOrderPrint(bt.leftChild);
4. PreOrderPrint(bt.rightChild)

public void preorderPrint(BinaryTreeNode bt) {


if (bt == null) return;
System.out.println(bt.value);
preorderPrint(bt.leftChild);
preorderPrint(bt.rightChild);
}
February 2, 2025
+ Binary Tree Operations: Depth First – 27

InOrder
Inorder (left, root, right)

 Three recursive steps are followed


 The nodes left subtree is traversed
 Visit the root node
 The nodes right subtree is traversed

February 2, 2025
+ Binary Tree : InOrder Traversal Algorithm / 28

Java Code
Algorithm: InOrderPrint
Input: a binary tree node bt
Output: display the tree content in a InOrder style

Method:
1. if (bt == null) return;
2. InOrderPrint(bt.leftChild);
3. Display(bt.value);
4. InOrderPrint(bt.rightChild)

public void inorderPrint(BinaryTreeNode bt) {


if (bt == null) return;
inorderPrint(bt.leftChild);
System.out.println(bt.value);
inorderPrint(bt.rightChild);
}
February 2, 2025
+ Binary Tree Operations: Depth First – 29

PostOrder
Postorder (left, right, root)

 Three recursive steps are followed


 The nodes left subtree is traversed
 The nodes right subtree is traversed
 Visit the root node

February 2, 2025
+ Binary Tree : PostOrder Traversal Algorithm 30

/ Java Code
Algorithm: PostOrderPrint
Input: a binary tree node bt
Output: display the tree content in a PostOrder style

Method:
1. if (bt == null) return;
2. PostOrderPrint(bt.leftChild);
3. PostOrderPrint(bt.rightChild)
4. Display(bt.value);

public void postorderPrint(BinaryTreeNode bt) {


if (bt == null) return;
postorderPrint(bt.leftChild);
postorderPrint(bt.rightChild);
System.out.println(bt.value);
}
February 2, 2025
+ Tree Operations: Traversal - Example 31

February 2, 2025
+ Students Slide 32

Breadth First Traversal:

Inorder Tree Traversal:

Preorder Tree Traversal:

Postorder Tree Traversal:


February 2, 2025
+ Students Slide 33

February 2, 2025
+ Students Slide inorder traversal 34

A/B*C*D+E
Arithmetic Expression Using BT infix expression

+ preorder traversal
+**/ABCDE
* E prefix expression

* D postorder traversal
AB/C*D*E+
postfix expression
/ C

level order traversal


A B +*E*D/CAB

February 2, 2025
+ Students Slide inorder traversal 35

A/B*C*D+E
Arithmetic Expression Using BT infix expression

+ preorder traversal
+**/ABCDE
* E prefix expression

* D postorder traversal
AB/C*D*E+
postfix expression
/ C

level order traversal


A B +*E*D/CAB

February 2, 2025
+ Type of Binary Tree: Binary Search Tree 36

(BST)
Binary Search Tree – A Binary Search Tree structure used
for searching. The following are some of the properties of BST
 Every node is ordered by some key data field(s)
 For every node in the tree, its key is greater than its left child’s
key and less than its right child’s key
 The BST is not allow to store duplicate values.

February 2, 2025
+ BST Operations - Insertion 37

Adding a new node to Binary Tree can be divided into two stages:
 search for a place to put a new element
 insert the new element to that place

Rule for Insertion

1. IF the new value == current node value THEN duplicate found and
exit

2. IF new value < current node's value, THEN go to the left subtree,

ELSE go to the right subtree.

 Following this simple rule, the algorithm reaches a node, which has no left or right subtree.

February 2, 2025
+ BST Operations - Insertion 38

 Initially, a new node has no children, so it is a leaf.


 Red circles indicate possible places for a new node.

February 2, 2025
+ BST Operations - Insertion 39


Insert 4 to the tree

February 2, 2025
+ BST Operations - Insertion 40

February 2, 2025
+ Student Slide – BST Insertion 41


Insert 19 to the tree

Insert -2 to the tree

Insert 6 to the tree


Insert 1 to the tree

Insert 18 to the tree

Insert 12 to the tree

Insert 3 to the tree

Insert 0 to the tree February 2, 2025
+ BST Operations - Insertion Algorithm: Insertion 42

Input: KeyVal
Output: Update Tree if Insertion
success
newNode = new Node(KeyVal, null, null,
null)

isEmpty(
Yes root = newNode, size=size + 1 Return
)
No
Current = root

Parent = Current

keyVal ==
Yes Display(“Duplicate found”); Return
current.value

No

keyVal < Current Parent.Left =


Yes Current= current.Left Yes Break
current.value == null newNode
No
No
Current Parent.Right =
Current= current.Right == null Yes Break
newNode newNode.Parent = Parent

No size = size + 1

February 2, 2025
+ BST Operations - Insertion 43

Algorithm: Insertion
Input: KeyVal
Output: Update Tree if Insertion success

Method:

1. Set newNode = new Node(KeyVal, null, null, null)

2. IF (isEmpty()) THEN set root = newNode, size=size + 1. Return

3. ELSE set current = root

1. Repeat un-limited Loop // return to leave the method without end of

loop

2. Parent = Current February 2, 2025


+ Tree Operations - Insertion 44

5. ELSE IF (keyVal < Current.value) THEN current =


Brea
current.Left. k

IF (current == null) THEN Set Parent. Left = newNode


Brea
[End If] k

6. ELSE current = current.Right.

IF (current == null) THEN Set Parent. Right =

newNode [End If]

7. [End If]
February 2, 2025
+ BST Operations - Searching 45

 Searching is very similar to Insertion operation.

 Search algorithm traverses the tree "in-depth", and compares


value of each visited node with the one, we are looking for.

 For example – Search for 3 in the tree,

February 2, 2025
+ Student Slide – BST Searching 46

findMin =

findMax =

Also draw lines for Minimum and Maximum


February 2, 2025
+ BST Operations – Searching (Algorithm) 47

Algorithm: Find [recursive


function]

Input: Node of a binary search tree, KeyVal


Output: return the searching node if found or return null

Method:
1. IF (Node== null) THEN display(“Searching fail”); return null
2. IF (KeyVal == Node.value) THEN return Node
3. IF (KeyVal < Node.value) THEN return (Find(Node.left, keyVal))
ELSE return
(Find(Node.Right, keyVal))
February 2, 2025
+ BST Operations - Deletion 48

 When we delete a node, we need to consider how we take


care of the children of the deleted node.

 First, we need to locate the node to be deleted

 Three cases arise.

February 2, 2025
+ BST Operations - Deletion 49

 Case 1: The node is a leaf


 Delete it immediately

 Case 2: The node has one child


 Replace the node with the childe node

February 2, 2025
+ BST Operations - Deletion 50

 Case 3: The node has 2 children


 Replace the node with the minimum element at the right subtree
 Delete that minimum element

February 2, 2025
+ Student Slides – BST Deletion (redraw the Tree) 51

February 2, 2025
+ Tree Operations – BST Deletion (draw the Tree) 52

February 2, 2025
+ BST Operations - Deletion 53

Case 1: The node is a leaf

Current.Left ==
null
AND Yes Parent = Current.Parent.
Current.Right ==
null

No Parent.value >
Yes Parent.Left=null
Current.value()

No
Case – II
Parent.Right = null

February 2, 2025
+ BST Operations - Deletion 54

Case 2: The node has one child

Case – II

Current.Left == null
OR Yes Parent = Current.Parent
Current.Right ==
null
Parent.Value > Current.Lef
No Current.Value
Yes Parent.Left =
t != null Yes Current.Left

No
No
Case – III Parent.Left=Current.Right.

Current.Right !=
null
Yes Parent.Right = Current.Right

No
Parent.Right = Current.Left

February 2, 2025
+ BST Operations - Deletion 55

Case – III
Case 3: The node has 2 children

minNode =
findMin(Current.getRight())

Current.setValue(minNode.getValue
())

Delete(minNode,
minNode.getValue())

End

February 2, 2025
+ Tree Operations - Delete 56

Algorithm: Delete
Input: Node of a binary search tree, KeyVal
Output: return update Tree

Method:
Set Current = find(root, keyVal)
// Case-I: Leaf node
1. IF (Current.Left == null AND Current. Right == null) THEN
Set Parent = Current.Parent.
IF (Parent.value > Current.value) THEN Set Parent. Left =
null.
ELSE Set Parent.Right = null [ End IF ]

// Case – II : Node has 1 child


2. ELSE IF (Current.Left == null OR Current.Right == null) THEN
Set Parent = Current.Parent. February 2, 2025
+ Tree Operations - Delete 57

IF (Parent.value > Current.value) THEN


IF (Current.Left != null ) THEN
Set Parent. Left =Current. Left
ELSE Set Parent.Left=Current.Right [ End If ]
ELSE
IF (Current.Right != null) THEN
Set Parent. Right =Current. Right.
ELSE Set Parent.Right =Current.Left [ End If ]
[ End IF ]
// Case – III: Node with 2 childs
3. ELSE
Set minNode = findMin(Current.Right)
Set Current.value = minNode.value
Delete(minNode, minNode.value) // delete the node
4. [End If]
February 2, 2025
+ Tree Implementation in Java (Lab 58

Section)

BST Node
Structure:
Parent

(Addres
(Address)

Right
(Address)

Left

s)
Value
(Store Data)

February 2, 2025
+ Tree Implementation in Java (Lab 59

Section)

February 2, 2025
+ Tree Implementation in Java (Lab 60

Section)
Create
Object

February 2, 2025
+ Tree Implementation in Java (Lab 61

Section)
The Outputs:

February 2, 2025
+ Tree Applications 62

Tree are important data structure to store and represent


data. The following are some of the Applications of the Tree

1. File System

Windows File System Linux File System February 2, 2025


+ Tree Applications 63

2. Trees are used in computer science

• To represent algebraic formulas,

• As an efficient method for searching large dynamic lists, for


example, Primary Key in Database

• For such diverse applications as artificial intelligence systems,


i.e. Knowledge representation and Dictionary data storing.

February 2, 2025
+ BST Tasks 64

 Exercise the provided programs in the Lab.

 Write the code for the following methods


 Find the maximum value
 Find the minimum value

February 2, 2025
+ BST Operations– Searching Minimum 65

value
public binaryNode findMin(binaryNode TreeNode){

if (isEmpty()) return null;

while(TreeNode.getLeft() != null )

TreeNode = TreeNode.getLeft();

return TreeNode;

February 2, 2025
+ BST Operations– Searching Maximum 66

value
public binaryNode findMax(binaryNode TreeNode){

if (isEmpty()) return null;

while(TreeNode.getRight() != null )

TreeNode = TreeNode.getRight();

return TreeNode;

February 2, 2025
+ 67

End of Tree part 1- Lec 08

February 2, 2025

You might also like