Professional Documents
Culture Documents
Trees
Trees
Trees
ancestors,
descendants, parent,
children,
leaves (vertices with no
children),
internal vertices
(vertices with children)
path
subtrees
order of nodes,
siblings,
T.U. Cluj-Napoca -DSA Lecture 2 - M. Joldos
m = 2 binary; m = 3 ternary
Some limits:
Traversals
Ancestral information
Traversal example
compound propositions,
combinations of sets, and
arithmetic expressions.
10
infix form:
11
12
ADT Tree
13
Example
14
15
16
17
18
19
BST implementation
typedef struct t_node
{
void *item;
struct t_node *left;
struct t_node *right
} NodeT;
20
21
key = 22;
if ( FindInTree( root ,
&key ) )
FindInTree( n, &key );
FindInTree(n->right,&key );
FindInTree(n->left,&key );
return n->item;
T.U. Cluj-Napoca -DSA Lecture 2 - M. Joldos
22
Find performance
Height, h
Number of nodes, n
n = 1 + 21 + 22 + + 2h
h = log2 n
= 2h+1 - 1
Complete Tree
Since we need at most h+1 comparisons,
find in O(h+1) or O(log n)
Same as binary search
T.U. Cluj-Napoca -DSA Lecture 2 - M. Joldos
23
21 to the tree
24
25
Cases of deletion
1. A leaf (simple)
2. A node with a
single child
3. A node with two
children
Example:
1. Delete 8, 13, 21 or
37
2. Delete 22
3. Delete 12, 20 or 29
26
27
28
BST Animation
http://people.ksp.sk/~kuko/bak/
29
BST performance
Find
c log n
Add
c log n
Delete
c log n
Apparently efficient in every
respect!
Take this list of characters and
form a tree
A B C D E F
unbalanced
30
Performance comparison
Add
Delete
Find
Arrays
Linked List
Trees
Simple, fast
Inflexible
O(1)
O(n) inc sort
O(n)
Simple
Flexible
O(1)
sort -> no adv
O(1) - any
O(n) - specific
O(n)
(no bin search)
Still Simple
Flexible
O(n)
O(logn)
binary search
O(log n)
31
Reading
AHU, chapter 3
CLR, chapters 11.3, 11.4
CLRS, chapter 10.4, 12
Preiss, chapter: Trees.
Knuth, vol. 1, 2.3
Notes
32