Académique Documents
Professionnel Documents
Culture Documents
leaves
branches
root
Computer Scientist’s View
root
leaves
branches
nodes
Linear Lists And Trees
• Linear lists are useful for serially ordered
data
– (e0, e1, e2, …, en-1)
– Days of week
– Months in a year
– Students in this class
• Trees are useful for hierarchically ordered
data
– Employees of a corporation
• President, vice presidents, managers, and so on
Hierarchical Data And Trees
b i
j k
c f
d e g h Subtrees
TREES
Caution: Some
texts start level
numbers at 0
rather than at 1
Terminology
• Node • Sibling
• Edge • Degree of a Tree
• Path • Ancestor
• Degree of a Node • Level
• Leaf or Terminal node • Height/Depth of a Tree
• Parent and Children • Forest
Binary Tree
• Finite (possibly empty) collection of elements
• A nonempty binary tree has a root element
• The remaining elements (if any) are partitioned into two
binary trees the left and right subtrees of the binary
tree
• Any node can have at most 2 children
b b
• are different when viewed as binary trees
• are the same when viewed as trees
Binary Tree Form and its Merits
• (a + b) * (c – d) / (e + f)
// The terms that we
introduced for
trees, such as
* + degree, level,
height, leaf, child
e f etc. all apply to
+ - binary tree in the
a b c d same way
minimum number of
nodes is h
Maximum Number Of Nodes
• All possible nodes at first h levels are present
• The maximum
number of nodes
on level i of a
binary tree is 2i-1
* +
e f
+ -
a b c d
Extended Binary Trees
number of external
nodes is n+1
Full Binary Tree
2 3
4 5 6 7
8 9 10 11 12 13 14 15
Node Number Properties
1
Let n be the number of
2 3 nodes in a binary tree
whose height is h.
4 5 6 7
8 9 10 11 12 13 14 15
2 3
• Complete
binary tree
4 5 6 7 with 10 nodes
8 9 10 11 12 13 14 15
The depth of a
Complete Binary Tree
with N nodes
is given by log2N +1
If N=1 000 000, then its
depth is 20
Binary Tree Representation
• Array/Sequential Representation
• Linked Representation
Array Representation
• Number the nodes using the numbering scheme
for a full binary tree. The node that is numbered i
is stored in tree[i].
a1
2 3
b c
4 5 6 7
d e f g
8 9 10
h i j
tree[] a b c d e f g h i j
0 5 10
Right-Skewed Binary Tree
a1
b 3
7
c
15
d
tree[] a - b - - - c - - - - - - - d
0 5 10 15
d e
struct node {
dataType data;
struct node *left, *right; g
f };
struct node *tree; h
In actual practice, an entire record may be stored at the node
Binary Trees- Linked Representation
• Other examples:
We also need a pointer variable ROOT or T or tree
Some Binary Tree Operations
• Determine the height.
• Determine the number of nodes.
• Make a clone.
• Determine if two binary trees are clones.
• Display the binary tree.
• Evaluate the arithmetic expression
represented by a binary tree.
• Obtain the infix form of an expression.
• Obtain the prefix form of an expression.
• Obtain the postfix form of an expression.