Title: Hierarchical Collections I
1Hierarchical Collections I
2What Is a Tree?
- Each item has at most one predecessor
- Each item can have many successors
3What Is a Tree?
Root node
- Start with a single node, called the root
4What Is a Tree?
Root node
- Start with a single node, called the root
- Each successor node is a child or daughter node
Daughters of root node
5What Is a Tree?
Root node
- Successors are also called descendants
Descendants of root node
6What Is a Tree?
Root node
- Nodes without successors are called leaf nodes
- The set of leaf nodes is the frontier
Leaf nodes (the frontier)
7What Is a Tree?
Root node
- Nodes with at least one successor are called
interior nodes
Interior nodes
8What Is a Tree?
Root node
- Predecessors are also called ancestors
- The immediate predecessor is called the parent
Ancestors of node X
9What Is a Tree?
Root node
- Nodes with the same parent are called siblings
Siblings
10What Is a Tree?
Root node
- Levels in a tree are numbered from 0
Level 0
Level 1
Level 2
Level 3
There are three nodes in level 3
11What Is a Tree?
Root node
- A binary tree allows at most two successors per
node
12What Is a Tree?
Root node
- A general tree allows any number of successors
per node
13Tree Applications
- File directories
- Processing sentences (computer programs or
natural languages) - Searchable data structures
- Heaps (implement heap sort, priority queues)
14A Parse (Expression) Tree
Source language program
The value of the expression
Ok or not OK
A parse tree
Syntax error messages
Semantic error messages
15Trees for Binary Expressions
- An expression tree for a number is a node
containing the number - Otherwise, the tree is a node containing an
operator and links to left and right subtrees - The subtrees contain the operands of the
expression
16Example Expression Trees
23
17Example Expression Trees
23
Root node Right subtree Left subtree
3 5
18Example Expression Trees
23
Root node Right subtree Left subtree
3 5
3 5 4
19Example Expression Trees
23
Root node Right subtree Left subtree
3 5
(3 5) 4
3 5 4
20Operator Precedence
(3 5) 4
3 5 4
Operators with higher precedence appear lower in
the tree, unless overridden by parentheses.
5 4 3
21Operator Precedence
5 4 - 3
5 4 - 3 6
5 4 - 3
When operators have equal precedence, the ones to
the left appear lower in the tree.