You are on page 1of 64

Trees

Dr. Nguyen Ho
Man Rang

Chapter 7
Trees Basic Tree
Concepts

Binary Trees
Data Structures and Algorithms Expression Trees

Binary Search
Trees

Dr. Nguyen Ho Man Rang


Faculty of Computer Science and Engineering
University of Technology, VNU-HCM

7.1
Trees
Outcomes
Dr. Nguyen Ho
Man Rang

• L.O.3.1 - Depict the following concepts: binary tree,


complete binary tree, balanced binary tree, AVL tree,
multi-way tree, etc.
• L.O.3.2 - Describe the strorage structure for tree Basic Tree
Concepts
structures using pseudocode. Binary Trees

• L.O.3.3 - List necessary methods supplied for tree Expression Trees

structures, and describe them using pseudocode. Binary Search


Trees
• L.O.3.4 - Identify the importance of “blanced” feature
in tree structures and give examples to demonstate it.
• L.O.3.5 - Identiy cases in which AVL tree and B-tree
are unblanced, and demonstrate methods to resolve all
the cases step-by-step using figures.

7.2
Trees
Outcomes
Dr. Nguyen Ho
Man Rang
• L.O.3.6 - Implement binary tree and AVL tree using
C/C++.
• L.O.3.7 - Use binary tree and AVL tree to solve
problems in real-life, especially related to searching
techniques. Basic Tree
Concepts
• L.O.3.8 - Analyze the complexity and develop Binary Trees
experiment (program) to evaluate methods supplied for Expression Trees
tree structures. Binary Search
Trees
• L.O.8.4 - Develop recursive implementations for
methods supplied for the following structures: list, tree,
heap, searching, and graphs.
• L.O.1.2 - Analyze algorithms and use Big-O notation to
characterize the computational complexity of algorithms
composed by using the following control structures:
sequence, branching, and iteration (not recursion).
7.3
Trees
Contents
Dr. Nguyen Ho
Man Rang

1 Basic Tree Concepts

Basic Tree
Concepts
2 Binary Trees Binary Trees

Expression Trees

Binary Search
Trees
3 Expression Trees

4 Binary Search Trees

7.4
Trees

Dr. Nguyen Ho
Man Rang

Basic Tree
Concepts

Basic Tree Concepts Binary Trees

Expression Trees

Binary Search
Trees

7.5
Trees
Basic Tree Concepts
Dr. Nguyen Ho
Man Rang
Definition
A tree (cây) consists of a finite set of elements, called nodes
(nút), and a finite set of directed lines, called branches
(nhánh), that connect the nodes.
Basic Tree
Concepts
a Binary Trees

Expression Trees

Binary Search
Trees

b c d

e f g h i

7.6
Trees
Basic Tree Concepts
Dr. Nguyen Ho
Man Rang
• Degree of a node (Bậc của nút): the number of
branches associated with the node.
• Indegree branch (Nhánh vào): directed branch toward
the node.
• Outdegree branch (Nhánh ra): directed branch away Basic Tree
Concepts
from the node.
Binary Trees

a For the node d: Expression Trees

Binary Search
• Degree = 4 Trees

• Indegree branches: ad
→ indegree = 1
b c d • Outdegree branches:
dg, dh, di
→ outdegree = 3

e f g h i
7.7
Trees
Basic Tree Concepts
Dr. Nguyen Ho
Man Rang
• The first node is called the root.
• indegree of the root = 0
• Except the root, the indegree of a node = 1
• outdegree of a node = 0 or 1 or more.
Basic Tree
Concepts

a root Binary Trees

Expression Trees

Binary Search
Trees

b c d

e f g h i

7.8
Trees
Basic Tree Concepts
Dr. Nguyen Ho
Terms Man Rang

• A root (nút gốc) is the first node with an indegree of


zero.
• A leaf (nút lá) is any node with an outdegree of zero.
• A internal node (nút nội) is not a root or a leaf. Basic Tree
Concepts
• A parent (nút cha) has an outdegree greater than zero. Binary Trees

• A child (nút con) has an indegree of one. Expression Trees

→ a internal node is both a parent of a node and a Binary Search


Trees
child of another one.
• Siblings (nút anh em) are two or more nodes with the
same parent.
• For a given node, an ancestor is any node in the path
from the root to the node.
• For a given node, an descendent is any node in the
paths from the node to a leaf.
7.9
Trees
Basic Tree Concepts
Dr. Nguyen Ho
Man Rang

Terms

• A path (đường đi) is a sequence of nodes in which each


node is adjacent to the next one. Basic Tree
Concepts

• The level (bậc) of a node is its distance from the root. Binary Trees

→ Siblings are always at the same level. Expression Trees

Binary Search
Trees
• The height (độ cao) of a tree is the level of the leaf in
the longest path from the root plus 1.

• A subtree (cây con) is any connected structure below


the root.

7.10
Trees
Basic Tree Concepts
Dr. Nguyen Ho
Level 0 a Man Rang

Branch ad

Level 1 b c d
Basic Tree
Concepts

Branch di Binary Trees

Expression Trees

Level 2 e f g h i Binary Search


Trees

• Parents: a, b, d • Internal nodes: b, d


• Children: • Siblings:
b, c, d, e, f, g, h, i {b, c, d}, {e, f }, {g, h, i}
• Leaves: c, e, f, g, h, i • Height = 3
7.11
Trees
Basic Tree Concepts
Dr. Nguyen Ho
Man Rang

a
Subtree b Subtree d
Basic Tree
Concepts

Binary Trees
b c d Expression Trees

Binary Search
Trees

e f g h i

7.12
Trees
Tree representation
Dr. Nguyen Ho
Man Rang

• organization chart • indented list


a
a
b
b c d e Basic Tree
Concepts

Binary Trees
e f g h i f Expression Trees

c Binary Search
Trees

• parenthetical listing d
g
a (b (e f ) c d (g h i))
h
i

7.13
Trees
Applications of Trees
Dr. Nguyen Ho
Man Rang

• Representing hierarchical data


Basic Tree
• Storing data in a way that makes it easily Concepts

Binary Trees
searchable (ex: binary search tree) Expression Trees

Binary Search

• Representing sorted lists of data Trees

• Network routing algorithms

7.14
Trees

Dr. Nguyen Ho
Man Rang

Basic Tree
Concepts

Binary Trees Binary Trees

Expression Trees

Binary Search
Trees

7.15
Trees
Binary Trees
Dr. Nguyen Ho
Man Rang

A binary tree node cannot have more than two subtrees.

a
Basic Tree
Left subtree Right subtree Concepts

Binary Trees

Expression Trees

Binary Search
b d Trees

e f g

7.16
Trees
Binary Trees Properties
Dr. Nguyen Ho
• To store N nodes in a binary tree: Man Rang
• The minimum height: Hmin = blog2 N c + 1 or
Hmin = dlog2 (N + 1)e
• The maximum height: Hmax = N

• Given a height of the binary tree, H:


Basic Tree
• The minimum number of nodes: Nmin = H Concepts
• The maximum number of nodes: Nmax = 2H − 1 Binary Trees

Expression Trees
Balance Binary Search
Trees
The balance factor of a binary tree is the difference in height
between its left and right subtrees.

B = HL − HR

Balanced tree:
• balance factor is 0, -1, or 1
• subtrees are balanced 7.17
Trees
Binary Trees Properties
Dr. Nguyen Ho
Man Rang
Complete tree

N = Nmax = 2H − 1 a
The last level is full.
b c Basic Tree
Concepts

d e f g Binary Trees

Expression Trees

Binary Search
Trees
Nearly complete tree

H = Hmin = blog2 N c + 1 a
Nodes in the last level are on
the left. b c

d e

7.18
Trees
Binary Tree Structure
Dr. Nguyen Ho
Definition Man Rang

A binary tree is either empty, or it consists of a node called


root together with two binary trees called the left and the
right subtree of the root.
Basic Tree
Concepts

Binary Trees

Expression Trees

Binary Search
Trees

7.19
Trees
Binary Tree Structure: Linked implementation
Dr. Nguyen Ho
Man Rang

node binaryTree
d a t a <dataType> r o o t <p o i n t e r >
l e f t <p o i n t e r > end b i n a r y T r e e
r i g h t <p o i n t e r >
end node Basic Tree
Concepts

Binary Trees
// G e n e r a l d a t a T y e : Expression Trees
dataType
k e y <keyType> Binary Search
Trees
f i e l d 1 <... >
f i e l d 2 <... >
...
f i e l d n <... >
end d a t a T y p e

7.20
Trees
Binary Tree Structure: Array-based implementation
Dr. Nguyen Ho
Suitable for complete tree, nearly complete tree. Man Rang

Basic Tree
Concepts

Binary Trees

Expression Trees

Binary Search
Trees
Hình: Conceptual

binaryTree
d a t a <a r r a y o f dataType>
end b i n a r y T r e e

Hình: Physical
7.21
Trees
Binary Tree Traversals
Dr. Nguyen Ho
Man Rang

• Depth-first traversal (duyệt theo chiều sâu): the


processing proceeds along a path from the root
through one child to the most distant descendent of
Basic Tree
that first child before processing a second child, i.e. Concepts

processes all of the descendents of a child before Binary Trees

going on to the next child. Expression Trees

Binary Search
Trees
• Breadth-first traversal (duyệt theo chiều rộng): the
processing proceeds horizontally from the root to all
of its children, then to its children’s children, i.e.
each level is completely processed before the next
level is started.

7.22
Trees
Depth-first traversal
Dr. Nguyen Ho
Man Rang

• Preorder traversal
• Inorder traversal
• Postorder traversal
Basic Tree
Concepts

Binary Trees

Expression Trees

Binary Search
Trees

7.23
Trees
Preorder traversal (NLR)
Dr. Nguyen Ho
Man Rang

In the preorder traversal, the root is processed first, before


the left and right subtrees.

Basic Tree
Concepts

Binary Trees

Expression Trees

Binary Search
Trees

7.24
Trees
Preorder traversal (NLR)
Dr. Nguyen Ho
Man Rang

Algorithm preOrder(val root <pointer>)


Traverse a binary tree in node-left-right
sequence.
Pre: root is the entry node of a tree or Basic Tree
Concepts

subtree Binary Trees

Expression Trees
Post: each node has been processed in Binary Search
Trees
order
if root is not null then
process(root)
preOrder(root->left)
preOrder(root->right)
end
Return 7.25
Trees
Inorder traversal (LNR)
Dr. Nguyen Ho
Man Rang

In the inorder traversal, the root is processed between its


subtrees.

Basic Tree
Concepts

Binary Trees

Expression Trees

Binary Search
Trees

7.26
Trees
Inorder traversal (LNR)
Dr. Nguyen Ho
Man Rang

Algorithm inOrder(val root <pointer>)


Traverse a binary tree in left-node-right
sequence.
Pre: root is the entry node of a tree or Basic Tree
Concepts

subtree Binary Trees

Expression Trees
Post: each node has been processed in Binary Search
Trees
order
if root is not null then
inOrder(root->left)
process(root)
inOrder(root->right)
end
Return 7.27
Trees
Postorder traversal (LRN)
Dr. Nguyen Ho
Man Rang

In the postorder traversal, the root is processed after its


subtrees.

Basic Tree
Concepts

Binary Trees

Expression Trees

Binary Search
Trees

7.28
Trees
Postorder traversal (LRN)
Dr. Nguyen Ho
Man Rang

Algorithm postOrder(val root <pointer>)


Traverse a binary tree in left-right-node
sequence.
Pre: root is the entry node of a tree or Basic Tree
Concepts

subtree Binary Trees

Expression Trees
Post: each node has been processed in Binary Search
Trees
order
if root is not null then
postOrder(root->left)
postOrder(root->right)
process(root)
end
Return 7.29
Trees
Breadth-First Traversals
Dr. Nguyen Ho
Man Rang

In the breadth-first traversal of a binary tree, we process all


of the children of a node before proceeding with the next
level.
Basic Tree
Concepts

Binary Trees

Expression Trees

Binary Search
Trees

7.30
Trees
Breadth-First Traversals
Dr. Nguyen Ho
Man Rang

Algorithm breadthFirst(val root


<pointer>) Basic Tree
Concepts
Process tree using breadth-first traversal. Binary Trees

Expression Trees

Pre: root is node to be processed Binary Search


Trees

Post: tree has been processed

currentNode = root
bfQueue = createQueue()

7.31
Trees
Breadth-First Traversals
Dr. Nguyen Ho
Man Rang

while currentNode not null do


process(currentNode)
if currentNode->left not null then
enqueue(bfQueue, currentNode->left)
end Basic Tree
Concepts
if currentNode->right not nul then Binary Trees
enqueue(bfQueue, currentNode->right) Expression Trees
end Binary Search
Trees
if not emptyQueue(bfQueue) then
currentNode = dequeue(bfQueue)
else
currentNode = NULL
end
end
destroyQueue(bfQueue)
End breadthFirst
7.32
Trees

Dr. Nguyen Ho
Man Rang

Basic Tree
Concepts

Expression Trees Binary Trees

Expression Trees

Binary Search
Trees

7.33
Trees
Expression Trees
Dr. Nguyen Ho
Man Rang

• Each leaf is an operand


• The root and internal nodes are operators
• Sub-trees are sub-expressions
Basic Tree
Concepts

Binary Trees

Expression Trees

Binary Search
Trees

7.34
Trees
Infix Expression Tree Traversal
Dr. Nguyen Ho
Man Rang

Basic Tree
Concepts

Binary Trees

Expression Trees

Binary Search
Trees

7.35
Trees
Infix Expression Tree Traversal
Dr. Nguyen Ho
Man Rang

Algorithm infix(val tree <pointer>)


Print the infix expression for an expression tree.
Pre: tree is a pointer to an expression tree
Post: the infix expression has been printed
if tree not empty then Basic Tree
Concepts
if tree->data is an operand then Binary Trees
print (tree->data) Expression Trees
else Binary Search
Trees
print (open parenthesis)
infix (tree->left)
print (tree->data)
infix (tree->right)
print (close parenthesis)
end
end
End infix
7.36
Trees
Postfix Expression Tree Traversal
Dr. Nguyen Ho
Man Rang

Algorithm postfix(val tree <pointer>)


Print the postfix expression for an
expression tree.
Basic Tree
Pre: tree is a pointer to an expression tree Concepts

Binary Trees
Post: the postfix expression has been Expression Trees

printed Binary Search


Trees
if tree not empty then
postfix (tree->left)
postfix (tree->right)
print (tree->data)
end
End postfix
7.37
Trees
Prefix Expression Tree Traversal
Dr. Nguyen Ho
Man Rang

Algorithm prefix(val tree <pointer>)


Print the prefix expression for an expression
tree. Basic Tree
Concepts
Pre: tree is a pointer to an expression tree Binary Trees

Post: the prefix expression has been printed Expression Trees

Binary Search
if tree not empty then Trees

print (tree->data)
prefix (tree->left)
prefix (tree->right)
end
End prefix
7.38
Trees

Dr. Nguyen Ho
Man Rang

Basic Tree
Concepts

Binary Search Trees Binary Trees

Expression Trees

Binary Search
Trees

7.39
Trees
Binary Search Trees
Dr. Nguyen Ho
Man Rang
Definition
A binary search tree is a binary tree with the following
properties:
1 All items in the left subtree are less than the root.
2 All items in the right subtree are greater than or equal Basic Tree
Concepts
to the root.
Binary Trees
3 Each subtree is itself a binary search tree. Expression Trees

Binary Search
Trees

7.40
Trees
Valid Binary Search Trees
Dr. Nguyen Ho
Man Rang

Basic Tree
Concepts

Binary Trees

Expression Trees

Binary Search
Trees

7.41
Trees
Invalid Binary Search Trees
Dr. Nguyen Ho
Man Rang

Basic Tree
Concepts

Binary Trees

Expression Trees

Binary Search
Trees

7.42
Trees
Binary Search Tree (BST)
Dr. Nguyen Ho
Man Rang

• BST is one of implementations for ordered Basic Tree


Concepts
list. Binary Trees

• In BST we can search quickly (as with Expression Trees

Binary Search
binary search on a contiguous list). Trees

• In BST we can make insertions and


deletions quickly (as with a linked list).

7.43
Trees
Binary Search Tree Traversals
Dr. Nguyen Ho
Man Rang

23

18 44
Basic Tree
Concepts

Binary Trees
12 20 35 52 Expression Trees

Binary Search
Trees

• Preorder traversal: 23, 18, 12, 20, 44, 35, 52


• Postorder traversal: 12, 20, 18, 35, 52, 44, 23
• Inorder traversal: 12, 18, 20, 23, 35, 44, 52

The inorder traversal of a binary search tree produces an


ordered list.
7.44
Trees
Binary Search Tree Search
Dr. Nguyen Ho
Man Rang
Find Smallest Node
Algorithm findSmallestBST(val root
<pointer>)
This algorithm finds the smallest node in a
Basic Tree
BST. Concepts

Binary Trees
Pre: root is a pointer to a nonempty BST Expression Trees

or subtree Binary Search


Trees

Return address of smallest node


if root->left null then
return root
end
return findSmallestBST(root->left)
End findSmallestBST
7.45
Trees
Binary Search Tree Search
Dr. Nguyen Ho
Man Rang
Find Largest Node
Algorithm findLargestBST(val root
<pointer>)
This algorithm finds the largest node in a
Basic Tree
BST. Concepts

Binary Trees
Pre: root is a pointer to a nonempty BST Expression Trees

or subtree Binary Search


Trees
Return address of largest node returned
if root->right null then
return root
end
return findLargestBST(root->right)
End findLargestBST
7.46
Trees
Binary Search
Dr. Nguyen Ho
Man Rang
Recursive Search
Algorithm searchBST(val root <pointer>,
val target <keyType>)
Search a binary search tree for a given Basic Tree

value. Concepts

Binary Trees

Expression Trees
Pre: root is the root to a binary tree or Binary Search
Trees
subtree
target is the key value requested

Return the node address if the value is


found
null if the node is not in the tree
7.47
Trees
Binary Search
Dr. Nguyen Ho
Man Rang
Recursive Search
if root is null then
return null
end
Basic Tree
Concepts

if target < root->data.key then Binary Trees

return searchBST(root->left, target) Expression Trees

Binary Search
else if target > root->data.key then Trees

return searchBST(root->right, target)


else
return root
end

End searchBST
7.48
Trees
Binary Search
Dr. Nguyen Ho
Man Rang
Iterative Search
Algorithm iterativeSearchBST(val root
<pointer>, val target <keyType>)
Search a binary search tree for a given Basic Tree

value using a loop. Concepts

Binary Trees

Expression Trees
Pre: root is the root to a binary tree or Binary Search
Trees
subtree
target is the key value requested

Return the node address if the value is


found
null if the node is not in the tree
7.49
Trees
Binary Search
Dr. Nguyen Ho
Man Rang

Iterative Search
while (root is not NULL) AND
(root->data.key <> target) do
Basic Tree
if target < root->data.key then Concepts

root = root->left Binary Trees

Expression Trees
else Binary Search
root = root->right Trees

end
end
return root
End iterativeSearchBST

7.50
Trees
Insert Node into BST
Dr. Nguyen Ho
Man Rang

Basic Tree
Concepts

Binary Trees

Expression Trees

Binary Search
Trees

All BST insertions take place at a leaf or a leaflike node (a


node that has only one null branch).
7.51
Trees
Insert Node into BST: Iterative Insert
Dr. Nguyen Ho
Man Rang

Algorithm iterativeInsertBST(ref root


<pointer>, val new <pointer>)
Insert node containing new data into BST Basic Tree
Concepts
using iteration. Binary Trees

Expression Trees

Pre: root is address of first node in a BST Binary Search


Trees

new is address of node containing data to


be inserted

Post: new node inserted into the tree

7.52
Trees
Insert Node into BST: Iterative Insert
Dr. Nguyen Ho
if root is null then Man Rang
root = new
else
pWalk = root
while pWalk not null do
parent = pWalk
Basic Tree
if new->data.key < pWalk->data.key then Concepts
pWalk = pWalk->left Binary Trees
else Expression Trees
pWalk = pWalk->right Binary Search
Trees
end
end
if new->data.key < parent->data.key then
parent->left = new
else
parent->right = new
end
end
End iterativeInsertBST 7.53
Trees
Insert Node into BST: Recursive Insert
Dr. Nguyen Ho
Man Rang

Algorithm recursiveInsertBST(ref root


<pointer>, val new <pointer>)
Insert node containing new data into BST
Basic Tree
using recursion. Concepts

Binary Trees

Expression Trees
Pre: root is address of current node in a Binary Search
Trees
BST
new is address of node containing data to
be inserted

Post: new node inserted into the tree

7.54
Trees
Insert Node into BST: Recursive Insert
Dr. Nguyen Ho
Man Rang
if root is null then
root = new
else
if new->data.key < root->data.key
Basic Tree
then Concepts

recursiveInsertBST(root->left, new) Binary Trees

Expression Trees
else Binary Search

recursiveInsertBST(root->right, Trees

new)
end
end
Return
End recursiveInsertBST
7.55
Trees
Delete node from BST
Dr. Nguyen Ho
Man Rang

Basic Tree
Concepts

Binary Trees

Expression Trees

Binary Search
Trees

Deletion of a leaf: Set the deleted node’s parent link to


NULL. 7.56
Trees
Delete node from BST
Dr. Nguyen Ho
Man Rang

Basic Tree
Concepts

Binary Trees

Expression Trees

Binary Search
Trees

Deletion of a node having only right subtree or left subtree:


Attach the subtree to the deleted node’s parent. 7.57
Trees
Delete node from BST
Dr. Nguyen Ho
Man Rang

Basic Tree
Deletion of a node having both subtrees: Concepts

Binary Trees
Replace the deleted node by its predecessor or Expression Trees

by its successor, recycle this node instead. Binary Search


Trees

7.58
Trees
Delete node from BST
Dr. Nguyen Ho
Man Rang

Basic Tree
Concepts

Binary Trees

Expression Trees

Binary Search
Trees

7.59
Trees
Delete node from BST
Dr. Nguyen Ho
Man Rang

Basic Tree
Concepts

Binary Trees

Expression Trees

Binary Search
Trees

7.60
Trees
Delete node from BST
Dr. Nguyen Ho
Man Rang
Algorithm deleteBST(ref root <pointer>,
val dltKey <keyType>)
Deletes a node from a BST.
Basic Tree
Pre: root is pointer to tree containing Concepts

Binary Trees
data to be deleted Expression Trees

dltKey is key of node to be deleted Binary Search


Trees

Post: node deleted and memory recycled


if dltKey not found, root unchanged

Return true if node deleted, false if not


found
7.61
Trees
Delete node from BST
Dr. Nguyen Ho
Man Rang

if root is null then


return false Basic Tree
Concepts
end Binary Trees

if dltKey < root->data.key then Expression Trees

return deleteBST(root->left, dltKey) Binary Search


Trees

else if dltKey > root->data.key then


return deleteBST(root->right, dltKey)

7.62
Trees
Delete node from BST
Dr. Nguyen Ho
Man Rang
else
// Deleted node found – Test for leaf
node
if root->left is null then Basic Tree
dltPtr = root Concepts

Binary Trees
root = root->right Expression Trees

recycle(dltPtr) Binary Search


Trees

return true
else if root->right is null then
dltPtr = root
root = root->left
recycle(dltPtr)
return true
7.63
Trees
Delete node from BST
Dr. Nguyen Ho
else Man Rang

// ...
else
// Deleted node is not a leaf.
// Find largest node on left subtree
dltPtr = root->left Basic Tree
Concepts
while dltPtr->right not null do Binary Trees
dltPtr = dltPtr->right Expression Trees
end Binary Search
Trees
// Node found. Move data and delete leaf
node
root->data = dltPtr->data
return deleteBST(root->left,
dltPtr->data.key)
end
end
End deleteBST
7.64

You might also like