8.0 Tree Data Structure - Notes
8.0 Tree Data Structure - Notes
Node
Edge
Binary Tree
• Binary Tree is a special data structure used for data storage purposes.
• A binary tree has a special condition that each node can have a
maximum of two children.
• A binary tree has the benefits of both an ordered array and a linked
list as search is as quick as in a sorted array and insertion or deletion
operation are as fast as in linked list.
Tree Traversal
• Depth-first approach
identifies the root node and visits all the grandchildren of the left then
right sub-tree or the right sub-tree then the left sub-tree
• In-order Traversal
• Pre-order Traversal
• Post-order Traversal
Tree Traversal
A→B→C→D→E→F→G
In-Order Traversal
• In this traversal method, the left subtree is visited
first, then the root and later the right sub-tree.
• We should always remember that every node may
represent a subtree itself.
• We start from A, and following in-order traversal, we
move to its left subtree B. B is also traversed in-
order.
• The process goes on until all the nodes are visited.
The output of inorder traversal of this tree will be −
D→B→E→A→F→C→G
In-Order Traversal
A→B→D→E→C→F→G
Pre-order Traversal
• D→E→B→F→G→C→A
Post-order Traversal
6 2 Breadth-f:
Pre-order:
In-order:
8 4 7 Post-order:
5 9
Exercises on Tree Traversal
j Determine the Breadth, In-order, Pre-order and Post-order
f e Pre-order:
In-order:
Post-order:
d a i Breadth:
g b
Types of Binary Tree
1. Full Binary Tree if every node has 0 or 2 children.
1 1
2 3 2 3
4 5 6 7 4 5
Types of Binary Tree
2. Complete Binary Tree if all the levels are completely filled except
possibly the last level and the last level has all keys as left as
possible.
1
2 3
4 5 6
Types of Binary Tree
3. Perfect Binary Tree if all the internal nodes have two children and
all leaf nodes are at the same level.
Types of Binary Tree
4. Balanced Binary Tree if the height of the left and right sub-tree of
any node differ by not more than 1.
diff = | height of left child – height of right child |
diff = 1 diff = 2
diff = 0 diff = 0
Types of Binary Tree
5. Degenerate Binary Tree if every internal node has one child.
Binary Tree Implementation
1. class Node:
2. def __init__(self,key):
3. self.left = None
4. self.right = None
5. self.val = key
Binary Tree Implementation
root
1. class Node: 1
2. def __init__(self,key):
3. self.left = None
4. self.right = None 2 3
5. self.val = key
6.
7. root = Node(1) 4
8. root.left = Node(2);
9. root.right = Node(3);
10. root.left.left = Node(4);