You are on page 1of 24

Data Structures Using C++ 2E

Chapter 11
Binary Trees and B-Trees
Binary Trees (cont’d.)
• Tree is a hierarchical data structure. Main uses of
trees include maintaining hierarchical data,
providing moderate access and insert/delete
operations. Binary trees are special cases of tree
where every node has at most two children.

2
3
4
types of binary

1. Full Binary Tree


A Binary Tree is full if every node has 0 or 2 children.
We can also say a full binary tree is a binary tree
in which all nodes except leaves have two
children.

5
6
• Complete Binary Tree: A Binary Tree is complete
Binary Tree if all levels are completely filled except
possibly the last level and the last level has all keys
as left as possible

7
8
• Perfect Binary Tree A Binary tree is Perfect Binary
Tree in which all internal nodes have two children
and all leaves are at the same level.

9
• A degenerate (or pathological) tree A Tree
where every internal node has one child. Such
trees are performance-wise same as linked list.

10
Binary Trees (cont’d.)
• Level of a node
– Number of branches on the path
• Height of a binary tree
– Number of nodes on the longest path from the root to a leaf
– See code on page 604
Root: (A) level 0 is parent for B, C

Leaves : G, E, H

Tree Height = 4

D is on level 2

FIGURE 11-1 Binary tree


Data Structures Using C++ 2E 11
12
Tree Traversals

• Unlike linear data structures (Array, Linked List,


Queues, Stacks, etc) which have only one logical
way to traverse them, trees can be traversed in
different ways. Following are the generally used
ways for traversing trees.

13
Depth First Traversals:

1. Inorder (Left, Root, Right) :


42513
2. Preorder (Root, Left, Right) :
1245
3. Postorder (Left, Right, Root)
:45231

14
Binary Tree Traversal (cont’d.)
• Inorder traversal
– Traverse the left subtree
– Visit the node
– Traverse the right subtree

D G B E A C H F

• Preorder traversal
– Visit the root FIGURE 11-1 Binary tree

– Traverse the left subtree


– Traverse the right subtree
A B D G E C F H

Data Structures Using C++ 2E 15


Binary Tree Traversal (cont’d.)
• Postorder traversal
– Traverse the left subtree
– Traverse the right subtree
– Visit the root

G D E B H F C A
FIGURE 11-1 Binary tree
• Each traversal algorithm: recursive
• Listing of nodes
– Inorder sequence
– Preorder sequence
– Postorder sequence
Data Structures Using C++ 2E 16
17
18
19
20
21
22
23
24

You might also like