Trees
Trees
Hierarchies
B C D T3
T1
G H I J
E F
L M
T2
K
Applications of Tree Data Structure
• Trees are used to store simple as well as complex
data. Here simple means an int value, char value
and complex data (structure).
• A node u is a descendant of v if
there is a path from v to u.
Height & Depth
Depth = 3 Numbers
0 in nodes
Depth = 1 2 give
1 heights
Depth = 0 0 0 1
2
Depth = 0 0
3 0
Subtrees, forests, and graphs
r1
r2
r3 r4 ≠ r4 r3 r1 r2
Singl Empt
Only Only
e y
left right
node Binar
child child
y
Tree
Small binary
tree:
Full and Complete Binary
Trees
• If every node has either 0 or 2 children, a binary tree is
called full.
Replace each
missing child with
external node
Do you need a
special flag to tell
which nodes are
Binary Extended binary
external?
tree tree
Every internal node has exactly 2 children.
B C D B C D
E E
E F G E F G
H H
Proof. By induction on n.
X(n) := number of external nodes in binary tree with
n internal nodes.
k nodes n-k-1
(for some 0 nodes Related to Thm
≤ k < n) 5.2 in your
Alternative Proof
Every node except the root has a parent, for a total of n - 1 nodes
with parents. These n - 1 parented nodes are all children, and each
0 ≤ i < h.
= 2 × N(h - 1) + 1
= 2 × (2h-1+1 - 1) + 1
= 2 × 2h - 2 + 1
Full Binary Tree Theorem
Thm. In a non-empty, full binary tree, the number of internal
nodes is always 1 less than the number of leaves.
Proof. By induction on n.
L(n) := number of leaves in a non-empty, full tree of n internal
nodes.
Thus: L(n) = n + 2 - 1 = n + 1.
Implicit representation
Sequential / Linear representation, using arrays.
Explicit representation
Linked representation, using pointers.
Sequential representation(Using 1D Array )
D 3 E F G
Mappin
g
of nodes
H I J K L M
to
integers
A B C D E F G H I J K L M
0 1 2 3 4 5 6 7 8 9 10 11 12 13
14
Sequential representation- Merits and
Demerits
Merits
• Random and Faster Access-Any node can be
accessed from any other node by calculating the
index.
• Space -Here, data are stored simply without any
pointers to their successor or predecessor.
• Easy -Inserting a new node and deletion of an
existing node is easy.
Demerits-
• Wastage of Space- If binary tree becomes
unbalanced(skewed) there will be lots of unused
array cells
• Limited size- Can store fixed size of binary tree
Linked Representation of Binary Trees
2 7
1 3 9
4
1 1 8
2 x 7
x 1 3 x 9 x
x 1 x x 1 x x 8 x
Operations on Binary tree
• Traversal
• Insertion of a node
• Deletion of a node
• Searching
• Height of a tree
• Depth of a node
• Number of nodes in tree