05 Trees Part1 BinaryTrees
05 Trees Part1 BinaryTrees
Trees - Part 1 1
Why are Trees needed?
Trees - Part 1 2
Learning Outcomes
LO4.1 Define general tree, Binary Tree and Binary Search Tree (BST).
LO4.2 Given a BST , draw resulted tree after an insert/ delete operations
LO4.3 Find the smallest and largest elements, number of nodes in a
tree and its’ height.
LO4.4 Write code to implement features of a binary search tree, such
as insertion, deletion, searching, traversals, nodes and height
calculation, rotation ...
LO4.5 Derive the time complexities for the above operations on a BST.
LO4.6: Compare a BST over other data structures
LO4.7: Identify applications where a binary search tree will be useful.
LO4.8: Define balanced BST and explain simple balancing algorithm
LO4.9: Define AVL Tree and explain by examples the insertion and
deletion operations in it.
LO4.10: Define heap and explain its’ application.
Trees - Part 1 3
Contents (from textbook)
Trees - Part 1 4
Contents (from textbook)
Part 3: Heaps
9.3 Heaps - 370
9.3.1 The Heap Data Structure - 370
9.3.2 Implementing a Priority Queue with a Heap - 372
Trees - Part 1 5
Part 1:
Trees and
General Binary Trees
(2 slots)
Trees - Part 1 6
Objectives
What is tree?
What are tree’s properties?
How to describe a node?
How to manager a tree?
How to used binary tree instead of n-ary tree
Algorithms:
Add new node
Traversals and applications:
Gettingminimum, maximum value stored in a binary tree
Getting tree’s height
Trees - Part 1 7
General Trees: Definitions
A tree is a data type that consists of nodes and arcs (edges) A tree
can be empty
Rooted tree: A tree in which a specific node is chosen as ROOT(a
reference in practice).
A tree is depicted upside down with the root at the top.
Level 5
Level 6
Trees - Part 1 10
General Trees: Definitions
•Ancestors/
predecessors of
current node
• Current node
•Descendants
/ successors
of current
node
Trees - Part 1 11
General Trees: Application Demo.
Trees - Part 1 13
General Trees: Definitions…
Binary tree can be used instead of n-ary tree:
- References to children have their own meaning.
class BinTreeNode{
Object data;
BinTreeNode left; The first child
BinTreeNode right; The next sibling
}
t = root.left; // con cả của ông tổ
while( t!= null) {
process (t); // xử lý cây con cả
t = t.right; // sang xử lý các cây con kế
}
Trees - Part 1 14
General Trees: Orderly Trees
-Ternary tree
- Criterion:
value in father
node must be
less than those
in children.
Trees - Part 1 15
General Binary Tree (Binary Trees)
A binary tree is a tree whose nodes have two children
(possibly empty), and each child is designated as either a
left child or a right child
In Binary tree, each node may have at most two
children.
class BinTreeNode {
Object data;
BinTreeNode left;
BinTreeNode right;
}
Examples of binary trees
Trees - Part 1 16
Binary Trees: Complete BT
In a perfect (hoàn hảo) binary tree, all non-
terminal nodes have both their children, and all
leaves are at the same level Shortest tree,
all path lengths from the root to leaves are
the same.
- Complete (đầy đủ) binary tree: all non-
terminal nodes have both their children.
Degraded tree
Cây suy biến
Trees - Part 1 18
Binary Trees: Complete BT
Complete BT: Relation between leaves and non-terminal nodes
leaves= non-terminals + 1
Trees - Part 1 19
Binary Trees: Decision Trees
A decision tree is a binary tree in which all nodes have
either zero or two nonempty children.
Decision tree is a means to model a real-world decision
Trees - Part 1 20
Binary Search Trees (BST)
Trees - Part 1 22
BT Imp. : An Array as a Binary Tree
Index 0 1 2 3 4 5 6 7 8 9
Array 20 10 15 8 7 13 14 2 5 6
Trees - Part 1 23
BT Imp. : An Array as a Binary Tree
Case 2: There is NO rule to specify father-child relations
Root: Element at the position 0.
Child indices must be stored 3 arrays (Info, Left, Right)
Trees - Part 1 24
BT Imp. : Linked-Structured BT
Declarations:
Trees - Part 1 25
BT Imp. : Algorithms on BT
Trees - Part 1 26
BT Imp. : Algorithms on BT…
Trees - Part 1 27
BT Imp. : Algorithms on BT…
Tree Traversal:
Tree traversal is the process of visiting each node in the tree
exactly one time O(number of nodes)
Breadth-first traversal is visiting each node starting from
the lowest (or highest) level and moving down (or up) level
by level, visiting nodes on each level from left to right (or
from right to left)
Depth-first traversal proceeds as far as possible to the left
(or right), then backs up until the first crossroad, goes one
step to the right (or left), and again as far as possible to the
left (or right)
Trees - Part 1 28
BT Imp. : Algorithms on BT…
Breadth-First Traversal is called as level-based traversal also.
Levels will be traversed in top-down direction.
Nodes in a level will be traversed in left-to-right direction.
Node’s Address
1000
Result:
500 2000 13, 10, 25, 2, 12, 20, 31, 29
200 100 800 300 A figure of a queue
3000
Trees - Part 1 29
BT Imp. : Algorithms on BT…
Breadth-First Traversal
Queue
Result:
13, 10, 25, 2, 12, 20, 31, 29
Trees - Part 1 30
BT Imp. : Algorithms on BT…
Condition:
p != null Visiting the
node p: (N)
Traversing the
tree root p
3 operations: N, L, R.
Traversing the An specific order of
tree root p.left 3 operations gives us
(L) a specific traversal
such as NLR, RNL, …
Traversing the
tree root p.right
(R)
Trees - Part 1 31
BT Imp. : Algorithms on BT…
Depth-First Traversals:
Some recursive
implementations:
NLR
Trees - Part 1 32
BT Imp. : Algorithms on BT…
Depth-First Traversals: Practice
Results:
NLR:
7, 1, 3, 8, 9, 2, 15, 6, 13, 14, 5
LNR:
3, 1, 9, 8, 7, 15, 2, 13, 6, 5, 14
LRN:
3, 9, 8, 1, 15, 13, 5, 14, 6, 2, 7
Trees - Part 1 33
BT Imp. : Algorithms on BT…
Practice:
Give yourself 3 binary trees then write down results of:
Breadth-First traversals
Depth-First traversals
Trees - Part 1 34
BT Imp. : Algorithms on BT…
Depth-First Traversals: Implementation using stacks
(Eliminating recursion)
If (root==null) return;
Stack stk= new Stack();
BTNode node;
stk.push(root);
while (!stk.empty()) {
node= stk.pop();
LIFO visit (node);
if (node.right!=null) stk.push(node.right);
if (node.left!=null) stk.push(node.left);
}
Trees - Part 1 35
BT Imp. : Algorithms on BT…
Trees - Part 1 36
BT Imp. : Algorithms on BT…
Counting number of nodes in a BT
int countNodes() {
int count=0;
The breadth-first
if (root != null) {
traversal is modified Queue q = new Queue();
to count number of BTNode v;
tree’s nodes. q. enqueue (root);
while (! q.empty()) {
v = q.dequeue();
Visit(v)
count = count +1;
if (v.left != null) q.enqueue(v.left);
if (v.right != null) q.enqueue(v.right);
}
}
return count;
}
Trees - Part 1 37
BT Imp. : Algorithms on BT…
Get maximum/minimum data
<T> getMax() {
if (root == null) throws new Exception (“Empty tree”);
<T> result = root.data;
Queue q = new Queue();
BTNode v;
q. enqueue (root);
while (! q.empty()) {
v = q.dequeue();
Visit(v)
if (result < v.data) result = v.data;
if (v.left != null) q.enqueue(v.left);
if (v.right != null) q.enqueue(v.right);
Give yourself the }
algorithm for
return result;
getting minimum
data in a tree. }
Trees - Part 1 38
BT Imp. : Algorithms on BT…
int <T> getHeight() {
Get Tree’s Height if (root == null) return 0;
Tree’s height = max level of nodes. int maxLevel=0, curL;
Root has level 1 Queue q = new Queue<Node_Level>();
Node_Level nv;
class Node_Level { // utility class q. enqueue (new Node_Level(root, 1));
BTNode node while (! q.empty()) {
int level;
nv = q.dequeue(); curL = nv.level;
Node_Level (BTNode p, int L) {
node = p; if (maxLevel < curL) maxLevel = curL;
level = L; BTNode left = nv.node.left;
} BTNode right = nv.node.right;
} if (left != null)
q.enqueue(new Node_Level (left, curL +1));
if (right != null)
(13,1), (10,2), (25,2), (2,3), (12,3), (20,3), (31,3), (29,4) q.enqueue(new Node_Level(right, curL +1));
Queue }
return maxLevel;
}
Trees - Part 1 39
BT Imp. : Algorithms on BT…
Trees - Part 1 40
Summary
Trees - Part 1 41
Summary
Tree can be used to manage unorderly related nodes. Problems in which
data in current state are created from previous state (chess, human family,
manager-staff relations,…)
Orderly tree is a tree whose nodes are designated their positions based on a
pre-defined comparisional criteria.
Trees - Part 1 42
Ôn tập- Viết vào vở
1- Cây là gì?
2- Tại sao cây được gọi là cấu trúc liên kết phi tuyến?
3- Tại sao cây được gọi là cấu trúc phân lớp (hierachical structure)?
4- Hãy định nghĩa các khái niệm cơ bản liên quan đến cây: nút, cạnh, nút gốc, nút lá, nút
trung gian, mức của nút, chiều cao của cây.
5- Mô tả một nút trong cây bằng những gì?
6- Với góc nhìn hiệu suất, chiều cao của cây có ý nghĩa gì?
7- Với góc nhìn thực hành, mức độ phân nhánh của một nút (bậc của cây- cây n-phân) có
ý nghĩa gì?
8- Làm thế nào để cây nhị phân có thể biều diễn được cây n-phân?
9- Duyệt cây là gì?
10- Hãy vẽ 1 cây nhị phân tuỳ ý rồi cho kết quả của phép duyệt theo chiều rộng.
11- Hãy vẽ 1 cây nhị phân tuỳ ý rồi cho kết quả của phép duyệt theo chiều sâu theo thuật
toán pre-order traversal.
12- Hãy vẽ 1 cây nhị phân tuỳ ý rồi cho kết quả của phép duyệt theo chiều sâu theo thuật
toán in-order traversal.
13- Hãy vẽ 1 cây nhị phân tuỳ ý rồi cho kết quả của phép duyệt theo chiều sâu theo thuật
toán post-order traversal.
Trees - Part 1 43
Next part: Binary Search Trees
Trees - Part 1 44