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

ch05 Trees Nosolution

ch05_Trees_noSolution

Uploaded by

ww03975
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

ch05 Trees Nosolution

ch05_Trees_noSolution

Uploaded by

ww03975
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 57

Data Structures

Chapter 5: Trees

5-1
Pedigree Genealogical Chart
血統、家譜 宗譜的、家系的
Chery
l

Kevin Rosemar
y

John Terry Richard Kelly

Jack Mary Anthon Karen Joe Michelle Mike Angela


y

Ancestors of Cheryl: A binary tree


John and Terry are parents of Kevin. 5-2
Lineal Genealogical Chart
直系的、世襲的 宗譜的、家系的

Proto Indo-European

Italic Hellenic Germani


c

Osco-Umbrian Latin Greek North West

Osco Umbrian Spanis French Italian Icelandic Norwegia Swedish Low High Yiddish
h n

Modern European languages


Latin produces Spanish, French and Italian. 5-3
A Tree
degree(A) = 3 height = depth = 4
degree(B) = 2 node: A, B, C, …M
root Level
degree(C) = 1 parent of E: B
A
1
children of B: E, F
ancestors of E: A, B
B C D 2 descendants of B: E,
F, K, L
E F G H I J 3 leaf nodes (terminal
nodes): K, L, F, G,
M, I, J
K L M 4
nonleaf nodes (nonterminal nodes): **
5-4
Trees
• Definition: A tree is a finite set of one or
more nodes such that:
– There is a specially designated node called the
root.
– The remaining nodes are partitioned into n
0 disjoint ( 無交集的 ) sets T1, …, Tn, each of which
is a subtree.

5-5
Tree Terminologies (1)
• degree ( 分支度 ) of a node:
number of subtrees of the node.
• degree of a tree:
maximum degree of the nodes in the tree.
• leaf (terminal) node:
a node with degree zero A

• Siblings (brothers): B C D

the nodes with the same parent E F G H I J

K L M

5-6
Tree Terminologies (2)
• ancestors of a node:
all the nodes along the path from
the root to the node. A

• descendants of a node: B C D
all the nodes of its subtrees. E F G H I J
• level of a node:
K L M
the level of the node’s parent plus one.
Here, the level of the root is 1.
• height (depth) of a tree:
the maximum level of the nodes in the tree.
5-7
List Representation of a Tree
The tree is represented as a list:
A
(A (B (E (K, L), F), C(G), D(H (M), I, J)))
B C D

E F G H I J

K L M
A 0

B F 0 C G 0 D I J 0

E K L 0 H M 0
5-8
Representation of Trees
• Left child-right sibling tree
– two links (or pointers): left child and right
sibling

data
A
left child right sibling
B C D
A

B C D
E F G H I J

E F G H I J
K L M
K L M
5-9
Binary Trees

A A A

B C B
B C
D E F
C
D E F G
G H I
D
Binary tree H I
E

Skewed binary tree Complete binary tree


歪斜二元樹 完整二元樹 5-10
Binary Tree 二元樹

• A binary tree:
– a finite set of nodes that is either empty, or
consists of a root and two disjoint binary trees
called the left subtree and the right subtree.
• In a binary tree, we distinguish between the
order of the children; in a tree we do not.
A A

B B

Two different binary trees


5-11
Full Binary Tree
• The maximum number of nodes on level i of a
binary tree is 2i–1, i  1.
• The maximum number of nodes in a binary tree
of depth k is 2k – 1, k  1.
• A full binary tree of depth k is a binary tree of
depth k having 2k – 1 nodes, k  0.
1

2 3

4 5 6 7

5-12
8 9 10 11 12 13 14 15
Complete Binary Tree
• A complete binary tree with n nodes and
depth k is that its nodes correspond to the
nodes numbered from 1 to n in the full
binary tree of depth k.
• It can be represented by an array.
1
• Root is at a[1]. a[0] is not used.
2 3
i
parent(i)=  2 
4 5 6 7
** left_child(i)=
right_child(i)= 8 9
5-13
Linked Representation of Binary Trees
data

leftChild rightChild

leftChild data rightChild

5-14
Linked Representation of Binary Trees

5-15
Linked Representation of a Binary Tree

A
root

B C
A

D E F G
B C

H I
D 0 E 0 0 F 0 0 G 0

0 H 0 0 I 0

5-16
Binary Tree Traversal
• Preorder traversal:
1. root
2. left subtree
3. right subtree
• Inorder traversal:
1. left subtree
2. root
3. right subtree
• Postorder traversal:
1. left subtree
2. right subtree
3. root

5-17
Arithmetic Expression Trees
• Preorder Traversal: **
=> Prefix expression
• Inorder Traversal:
+
=> Infix expression
• Postorder Traversal: * E
=> Postfix expression
* D

/ C

A B
5-18
Preorder Traversal
template <class T>
void Tree <T>::Preorder()
{//Driver calls workhorse for traversal of entire tree
Preorder(root);
}

template <class T>


void Tree <T>::Preorder (TreeNode <T>
*currentNode)
{//Workhouse traverses the subtree rooted at currentNode
If (currentNode){
Visit(currentNode); //visit root
Preorder(currentNode->leftChild);
Preorder(currentNode->rightChild);
} 5-19
}
Inorder Traversal
template <class T>
void Tree <T>::Inorder()
{//Driver calls workhorse for traversal of entire tree
Inorder(root);
}

template <class T>


void Tree <T>::Inorder (TreeNode <T>
*currentNode)
{//Workhouse traverses the subtree rooted at currentNode
If (currentNode){
Inorder(currentNode->leftChild);
Visit(currentNode); //visit root
Inorder(currentNode->rightChild);
} 5-20
}
Postorder Traversal
template <class T>
void Tree <T>::Postorder()
{//Driver calls workhorse for traversal of entire tree
Postorder(root);
}

template <class T>


void Tree <T>::Postorder (TreeNode <T>
*currentNode)
{//Workhouse traverses the subtree rooted at currentNode
If (currentNode){
Postorder(currentNode->leftChild);
Postorder(currentNode->rightChild);
Visit(currentNode); //visit root
} 5-21
}
Level-Order Traversal
• Preorder, inorder and postorder traversals
all require a stack.
+
• Level-order traversal uses a queue.
* E
• Level-order traversal:
1. root * D
2. left child / C
3. right child. A B
• After All nodes on a level have been
visited, we can move down.

Level-order traversal: **5-22


Level-Order Traversal of a Binary Tree

+
* E
* D
/ C
A B
+*E*D/CAB 5-23
Threaded Binary Tree 引線二元樹

• Threading Rules
– A 0 rightChild field at node p is replaced by a
pointer to the node that would be visited after p
when traversing the tree in inorder. That is, it is
replaced by the inorder successor of p.
– A 0 leftChild link at node p is replaced by a
pointer to the node that immediately precedes
node p in inorder (i.e., it is replaced by the
inorder predecessor of p).

5-24
Threaded Binary Tree
A

B C
A
D E F G
B C
H I
D E F G

H I
Inorder sequence: HDIBEAFCG 5-25
A
Memory Representation of Threaded Tree
x->rightThread == TRUE B C
=> x->rightChild is a thread D E F G
(pointer to inorder successor)
x->rightThread == FALSE H I
=> x->rightChild is a pointer Inorder sequence: H D I B E A F C G
to the right child. f - f

A header is
added as the f A f
virtual root
f B f f B f

f D f t E t t D t t E t

t H t t I t t:true, f:false 5-26


Inorder Successor in Threaded Trees
• By using the threads, we can perform an inorder
traversal without making use of a stack.
T* ThreadedInorderIterator::Next()
{//Return the inorder successor of currentNode=x
ThreadedNode <T> *temp = currentNode -> rightChild;
if (!currentNode->rightThread) //real rightChild
while (!temp->leftThread) temp = temp ->
leftChild;
//a path of leftChild starting from rightChild of x A
currentNode = temp;
B C
if (currentNode == root) return 0;
else return &currentNode -> data;
D E F G
} Inorder sequence:
HDIBEAFCG H I 5-27
Insertion of r as the Right Child of s
in a Threaded Binary Tree (1)
Case 1: The right subtree of s is empty.

u u

s s

r r

before after 5-28


Insertion of r as the Right Child of s
in a Threaded Binary Tree (2)
Case 2: The right subtree of s is not empty.

s s

p r r

q p

q
before after 5-29
Inserting r as the Right Child of s

5-30
Priority Queue
• Maximum (minimum) finding: In a priority
queue, the element to be deleted is the one
with highest (or lowest) priority. It is easy
to get the maximum (minimum).
• Insertion: An element with arbitrary
priority can be inserted into the queue
according to its priority.
• max (min) priority queue: a data structure
supports the above two operations.

5-31
14 9 30

12 7 6 3 25

10 8 6 5 Max heaps

2 10 11

7 4 20 83 21

10 8 6 50 Min heaps
5-32
Max (Min) Heaps
• A max (min) heap is a complete binary tree in
which the key value in each node is no smaller
(larger) than the key values in its children (if any).
• Heaps are frequently used to implement priority
queues.
• Time complexity of a max (min) heap with n
nodes:
– Max (min) finding: O(1)
– Insertion: O(log n)
– Deletion: O(log n)

5-33
Insertion into a Max Heap
20 20
(a) (b)

15 2 15 2

14 10 14 10

(b)(c1) 20 21 (b)(c2)
Insert 5 Insert 21

15 5 15 20
5

14 10 2 14 10 2 5-34
Deletion from a Max Heap
(a) 21 (b) 2

15 20 15 20

14 10 2 14 10 2

(c) 2 (d) 20

15 20 15 2

14 10 14 10 5-35
Deletion from a Max Heap (Cont.)
(e) 20 10
(f)

15 2 15 2

14 10 14 10

(g) 10 (i) 15

15 2 14 2

14 10 5-36
Binary Search Trees
• A binary search tree is a binary tree. It may
be empty. If it is not empty, then it satisfies
the following properties:
– Every element has a key and no two elements
have the same key (i.e., the keys are distinct)
– The keys (if any) in the left subtree are smaller
than the key in the root.
– The keys (if any) in the right subtree are larger
than the key in the root.
– The left and right subtrees are also binary
search trees.

5-37
Binary Trees

20 30 60

15 25 5 40 70

14 10 22 65 80
2

Not binary search tree Binary search trees


5-38
Searching a Binary Search Tree
• Search for an element with key value k.
• If the root is 0, then this is an empty tree,
and the search is unsuccessful.
• Otherwise, compare k with the key in the
root.
 k==root: successful search.
 k < root: search the left subtree. 30
 k > root: search the right subtree.
5 40

2 35 80
5-39
Searching a Binary Search Tree

5-40
Insertion into a Binary Search Tree
30 30

5 40 5 40

2 (1) Insert 80 2 80

30
(2) Insert 35
5 40
Time complexity: O(h)
h: tree height
2 35 80
5-41
Deletion from a Binary Search Tree
30 30

5 40 Delete 35 5 40

2 35 80 2 80

30 5
Delete 30
5 40 5 40 2 40

2 80 2 80 80
5-42
Deletion from a Binary Search Tree
• Deletion of a node x:
– x is a leaf node: delete x directly.
– x has one child: move up the position of child to
x.
– x has two children: replace x with either inorder
successor (smallest in the right subtree, no left
child) or inorder predecessor (largest in the left
subtree, no right child).
• Time complexity: O(h), h:tree height

5-43
Selection Trees
• Goal: merge ( 合併 ) k ordered sequences (called
runs) in nondecreasing into a single ordered
sequence.
• Straightforward method: perform k – 1
comparisons each time to select the smallest one
among the first number of each of the k ordered
sequences.
• Better method: winner tree k=8
10 9 20 6 8 9 90 17
15 20 20 15 15 11 95 18
16 38 30 25 50 16 99 20
28
run1 run2 run3 run4 run5 run6 run7 run8
5-44
Winner Tree for k = 8

1
6
2 3
6 8
4 5 6 7
9 6 8 17
8 9 10 11 12 13 14 15
10 9 20 6 8 9 90 17

15 20 20 15 15 11 95 18
16 38 30 25 50 16 99 20
28

run1 run2 run3 run4 run5 run6 run7 run8


5-45
Winner Tree for k = 8

1
8
2 3
9 8
4 5 6 7
9 15 8 17
8 9 10 11 12 13 14 15
10 9 20 15 8 9 90 17

15 20 20 25 15 11 95 18
16 38 30 28 50 16 99 20

run1 run2 run3 run4 run5 run6 run7 run8


5-46
Winner Tree
• A winner tree is a complete binary tree in which
each node represents the smaller of its two
children. Thus, the root represents the smallest.
• Each leaf node represents the first record in the
corresponding run.
• Each nonleaf node represents the winner of a
tournament.
• Number of levels: log 2 (k  1)
• Total time for merging k runs: O(n log2k)

5-47
1
Winner Tree 6
2 3
6 8
4 5 7
6
9 6 8 17
8 9 10 11 12 13 14 15
10 9 20 6 8 9 90 17
6 Overall
0 winner
(6,8)
Loser Tree (6,9)
1
8 (8,17)
2 3
9 17
(9,10) (6,20) (8,9) (17,90
4 5 ) 7
6
10 20 9 90
9 10 11 12 13 14 15
10 9 20 6 8 9 90 17
5-48
run 1 2 3 4 5 6 7 8
Loser Tree
• Loser tree: A selection tree in which each
nonleaf node retains a pointer to the loser.
• Each leaf node represents the first record of
each run.
• An additional node, node 0, has been added
to represent the overall winner of the
tournament.

5-49
Forests
• Forest: a set of n ≥ 0 disjoint trees.
• If we remove the root of a tree, we obtain a
forest.
– E.g., removing the root of a binary tree
produces a forest of two trees.

A E G

B C D F H I
5-50
Representing a Forest with a Binary Tree
• leftChild=first child
• rightChild=next sibling

A forest of A E G
3 trees B C D F H I
A
A forest is represented B E
by a binary tree.
C F G
D H
I 5-51
Constructing a Binary Tree from Its
Inorder Sequence and Preorder Sequence

Inorder sequence: BCAEDGHFI


Preorder sequence: ABCDEFGHI

Step 1: Find the root Step 2: Do recursively


A A

B, C D, E, F, G, H, I B D, E, F, G, H, I
C

5-52
Number of Distinct Binary Trees

n = 2, b2=2 n = 3, b3=5
• Number of distinct binary trees with n nodes:
n 1
bn  bi bn  i  1 , n 1 , and b0 1, b1 1
i 0

bn

bi bn-i-1 5-53
Generating function, let B ( x)  bi x i
i 0

bn b0bn  1  b1bn  2  ...  bn  2b1  bn  1b0


B ( x) b0  b1 x  b2 x 2  b3 x 3  ...
2 2
B 2 ( x) b0  2b0b1 x  (2b0b2  b1 ) x 2  (2b0b3  2b1b2 ) x 3  ...
b1  b2 x  b3 x 2  b4 x 3  ....
With b0 b1 1, we get the identity
xB 2 ( x) B ( x)  1
Solving quadratics, we get
1 1 4x
B( x) 
2x
1 1 4x
Note : B ( x)  is infeasible, becasue
2x
2 xB( x) 1  1  4 x when x 0 , with B (0) b0 1 5-54
The binomial theorem :
k  k  k 0  k  k 1 1  k  k 2 2 k 0 k
( x  y )   x y    x y    x y  ...    x y
 0  1  2 k
Expanding (1  4 x )1 / 2 with the binomial theorem, we get
1  1/ 2 n
B( x )   1 
2x 
 
n 0  n 
 (  4 x ) 

1 1/ 2 1 1/ 2 2 1/ 2
 (1  (1    (  4 x )    (  4 x )    (  4 x )3  ...))
2x  1   2   3 
1/ 2 1 1/ 2 3 1/ 2 5 2 1/ 2 7 3
  ( 2 )    (  2 x )    ( 2 x )    (  2 x )  ...
 1   2   3   4 
 1/ 2 
   (  1) m 22 m 1 x m
m 0  m  1 5-55
The coefficient of x n :
 1/ 2 
bn   (  1) n 22 n 1
 n  1
1 1 1 1 1 1
(  1)(  2)(  3)...(  n  1)(  n )
2 2 2 2 2 2 (  1) n 22 n 1
1 2 3 ... n ( n  1)
( 2  1)( 4  1)(6  1)...( 2( n  1)  1)( 2n  1) n n!
 2 
1 2 3 ... n ( n  1) n!
1 3 5 ... ( 2n  3)( 2n  1) 2 4 6 ... 2n
 
1 2 3 ... n ( n  1) n!
( 2n )! 1  2n 
   
( n  1)( n! )( n! ) n  1  n  5-56
Number of Distinct Binary Trees
• bn are Catalan numbers:1, 1, 2, 5, 14, 42, 132, 429,
1430, 4862, 16796, 58786, 208012, 742900, 2674440,
9694845, 35357670, 129644790, 477638700,
1767263190, 6564120420, …
• Number of distinct binary trees with n nodes= bn
– b0=1, b1=1, b2=2, b3=5, b4=14, b5=42, …
• http://en.wikipedia.org/wiki/Catalan_number

5-57

You might also like