Professional Documents
Culture Documents
LECTURE 5
Trees
Reference links:
https://cs.nyu.edu/courses/fall17/CSCI-UA.0102-
007/notes.php
https://www.comp.nus.edu.sg/~stevenha/cs2040.html
[M.Goodrich, chapter 8]
3
Lecture outline
❑ Tree ADT
▪ Definitions
▪ Applications
❑ Binary Tree
▪ Definitions
▪ Implementations
• Linked Structure
• Array based
▪ Binary Tree Traversal
❑ Binary Tree Application
3
Tree ADT
Introduction
Why trees?
❑ Relationship
▪ A is a parent of B and C
▪ B and C are children of A
▪ B and C are siblings
(with the same parent A)
▪ D is an ancestor of B
▪ B is a descendant of A and D
❑ D is root (has no parent) – nút gốc
❑ F is leaf (has no children) – nút lá
Trees: definitions
❑ Height of a tree
– chiều cao của cây
▪ Maximum level of the
nodes in the tree
Trees: applications
❑ File systems
Trees: applications
❑ Arithmetic Expressions
(a+b) * (a-b) + 2
Binary Tree
Binary Tree: Definitions
❑ Binary Tree = 2-ary tree (cây nhị phân)
▪ Each node has at most 2 “ordered” children
▪ Two children: left child, right child
Binary Tree: Definitions
❑ Full Binary Tree – Cây nhị phân đầy đủ
▪ All nodes at a level < h have two children (where h is the
height of the tree)
Binary Tree: Definitions
❑ Complete Binary Tree – Cây nhị phân hoàn chỉnh
▪ Full down to level h-1
▪ Level h filled in from left to right.
Binary Tree: Definitions
❑ Full Binary Tree Properties
▪ Number of nodes in a full binary tree of height h is N = 2h - 1.
▪ Therefore, the height of a full binary tree is O(log N)
▪ h=4
▪ N = 15
For more detail see Code Fragment 8.10, 8.11 [M.Goodrich, p328]
Binary Tree: Array-Based
❑ Implement Binary Tree using Array
Nodes T[] 0 1 2 3 4 5
A
Data A B C D E F 0
Parent -1 0 0 1 2 4 B C
1 2
Left 1 -1 4 -1 -1 -1 D E
Right 2 3 -1 -1 5 -1 3 4
F
5
Nodes T[]
A B C D E Ø G Ø I K
1 2 3 4 5 6 7 8 9 10
Nodes T[]
A
A B C D E F G H I K 1
1 2 3 4 5 6 7 8 9 10 B C
2 3
Given that a node is stored in index D E F G
position i, what is the position of its 4 5 6 7
parent? left child? right child?
H I K
8 9 10
Tree ADT
A
1
B C
2 3
D E F G
4 5 6 7
H I K
8 9 10
H I K
8 9 10
H I K
8 9 10
H I K
8 9 10
2 3
5 6
4 7
12
10 11 13
24 25
+ + * a * + g b c * f d e
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Binary Tree
API
Methods
Implementation
Linked
Array
Structure