Professional Documents
Culture Documents
+
• Family Tree
• Parse Trees x *
– e.g. for x +(y *(z+w))
y +
z w
Rooted Trees
Basic Terminology
• nodes (vertices)
• root
a
• parent
b c d e
• children
• siblings
f g h i j
• degree
k l m
1
Trees - Recursive Definition
• The empty tree L has no nodes
• Given trees T1, T2, …, Tk
with roots r1, r2, …,rk respectively,
and a node r,
we can form the tree T by making r the root,
and making r1, r2, …,rk the children of r
r
T1 Tk
T2
Intro to Data Structures and Algorithms © ADT - Trees, Slide 3
• leaf
f g h i j
• height
• depth
k l m
2
Example - Book
• Book Book
– Chapter 1
• Section 1.1 Ch 1 Ch 2 Ch 3
• Section 1.2
– Chapter 2 S 1.1 S 1.2 S 2.1 S 2.2 S 2.3
• Section 2.1
– Subsection 2.1.1
– Subsection 2.1.2 S 2.1.1 S 2.1.2
• Section 2.2
• Section 2.3
– Chapter 3
Intro to Data Structures and Algorithms © ADT - Trees, Slide 5
Ordered Trees
The children of each node are ordered
a a
¹
b c c b
Leftmost-Child
Right-Sibling
3
Binary Trees
Recursive Definition: root
A binary tree
• contains no nodes (L),
or,
left right
• has 3 disjoint sets of nodes:
– a root
– a binary subtree called its left subtree
– a binary subtree called its right subtree
Example
Binary Trees 3
3
¹ 2 7
2 7
4 1 5
4 1 5
Ordered Tree
Binary Tree 6
6
4
Full Binary Tree:
Each node either 3
• has degree 0 = is a leaf
or
• has degree 2 2 7
4 1 5
Positional Trees
Recursive Definition:
A k-ary tree
• contains no nodes (L),
or,
• has k+1 disjoint sets of nodes:
– a root
– k k-ary sub-trees
5
Complete Binary Tree
6
Tree ADT
Make-Tree(r,T1,…,Tk) - make a tree T with root r
and T1,T2,…,Tk as its sub-trees
7
Trees - Implementation
1
2 3
4 5 9 10
6 7 8
1 2 3 4 5 6 7 8 9 10
0 1 1 2 2 5 5 5 3 3
Parent representation
Intro to Data Structures and Algorithms © ADT - Trees, Slide 15
Trees - Implementation
root
1 2 3
1 2 4 5
3 9 10
2 3
4
5 6 7 8
4 5 9 10
6
7
6 7 8
8 root 1
10
head
Intro to Data Structures and Algorithms © ADT - Trees, Slide 16
8
Binary Tree Data structure
root
.
.
.
Parent
9
Tree Data structure
root
B C D
Example E F G H
0 A -1 1 -1
1 B 0 -1 2
2 C 0 4 3
3 D 0 7 -1
4 E 2 -1 5
5 F 2 -1 6
6 G 2 -1 -1
7 H 3 -1 -1
10
Example
0 A -1 1 -1
1 B 0 -1 2
2 C 0 3 -1
3 D 2 -1 4
4 E 2 -1 -1
5 F -1 6 -1
6 G 5 -1 -1
Tree Walks
InOrder-Tree-Walk(x)
1 if x ¹ NIL
2 InOrder-Tree-Walk(left[x])
3 print key[x]
4 InOrder-Tree-Walk(right[x])
PreOrder-Tree-Walk(x) PostOrder-Tree-Walk(x)
1 if x ¹ NIL 1 if x ¹ NIL
2 print key[x] 2 PostOrder-Tree-Walk(left[x])
3 PreOrder-Tree-Walk(left[x]) 3 PostOrder-Tree-Walk(right[x])
4 PreOrder-Tree-Walk(right[x]) 4 print key[x]
11
Example
1
2 3
4 5 6 7
8 9
PreOrder: 1 2 4 5 8 3 6 9 7
InOrder: 4 2 8 5 1 6 9 3 7
PostOrder: 4 8 5 2 9 6 7 3 1
Example:
+
Arithmetic Tree:
a *
- +
b c d e
PreOrder: + a * - b c + d e
InOrder: ( (a) + ( (b-c) * (d+e) ) )
PostOrder: a b c – d e + * +
12