Professional Documents
Culture Documents
Tree Data Structure
Tree Data Structure
STRUCTURE
Tree
• Tree is a non-linear data structure where the relations are hierarchical.
• Some objects are "above" and some are "below" others.
• The main terminologies used for tree are "parent", "child", "ancestor" and
"descendant“.
The top element of the tree is called the root of the tree but is drawn as the
highest element. The other elements are connected below.
• Path :path is a sequence of nodes (a0, a1, ..., an) where ak+ 1is a child of ak
B C D
E F G H
I J K Root = A
B C D
E F G H
I J K Leaves?
E, I, J, K, G, H, D
B C D
E F G H
Siblings?
K (E,F)
I J
(G , H)
(I , J , K)
2/12/2020 PREPARED BY TASNEEA HOSSAIN 10
A
B C D
E F G H
Depth of F ?
I J K
2
B C D
E F G H
B C D
E F G H
Degree of C?
I J K
2
• A binary tree is an ordered tree in which every node has at most two children.
• If each node of a tree has either zero or two children, the tree is called a
proper (strictly) binary tree.
A A
B C B C
D E F
E F G H
Binary tree
B C
Full node
D E F
D E F
/ +
x + x 6
+ 3 - 2 3 -
3 1 9 5 7 4
C
B
E F I G
B C
E F I G
B C
E F I G
B C
E F I G
B C
E F I G
B C
E F I G
B C
E F I G
B C
E F I G
B C
E F I G
Algorithm inOrder(v)
if isInternal (v)
inOrder (leftChild (v))
visit(v)
if isInternal (v)
inOrder (rightChild (v))
B C
E F I G
B C
E F I G
B C
E F I G
B C
E F I G
B C
E F I G
B C
E F I G
B C
E F I G
2/12/2020
Inorder traversal: EBFAICG
PREPARED BY TASNEEA HOSSAIN 42
Postorder
• In postorder traversal, a node is visited after its descendants
Algorithm
postOrder(v)
for each child w of v
postOrder (w)
visit(v)
C
B
E F I G
C
B
E F I G
C
B
E F I G
C
B
E F I G
C
B
E F I G
C
B
E F I G
C
B
E F I G
Preorder: PFBHGSRYTWZ
Inorder: BFGHPRSTWYZ
Postorder: BGHFRWTZYSP
B C
D E F G
H I
H I
Recursive definition:
A binary tree with a single node is a complete binary tree of height h = 0 and a
complete binary tree of height h is a tree where either:
• The left sub-tree is a complete tree of height h–1 and the right sub-tree is a perfect
tree of height h–2, or
• The left sub-tree is perfect tree with height h–1 and the right sub-tree is complete
tree with height h–1
6 4 7
3
9 0 1 2 3 4 5 6 7 8 9
12 1 5 6 4 3 7 9
Similarly, in case of deletion, the last element in the array has to be deleted if we
want to maintain the complete-tree structure.
A D
C K
C K
65
G
C I
A D H J
B F L
E K
G C I A D H J B F L E K